fail模块场景(ansible)

更多见博客 : //blog.csdn.net/qq_35887546/article/details/105242720

 

创建剧本 /home/alice/ansible/lvm.yml,用来为所有受管机完成以下部署:

  • 1)在卷组 search 中创建名为 mylv 的逻辑卷,大小为 1000MiB

  • 2)使用 ext4 文件系统格式化该逻辑卷

  • 3)如果无法创建要求的大小,应显示错误信息 insufficient free space,并改为 500MiB

  • 4)如果卷组 search 不存在,应显示错误信息 VG not found

  • 5)不需要挂载逻辑卷

 

 

一、fail模块

在编写shell脚本时,有可能会有这样的需求,当脚本执行到某个阶段时,需要对某个条件进行判断,如果条件成立,则立即终止脚本的运行,在shell脚本中实现这个需求很简单,只需要在条件成立时调用”exit”命令即可终止脚本的运行, 那么在编写playbook时,如果有类似的需求,我们该怎么办呢?

想要在playbook中按照我们的意愿中断剧本的执行,其实也很简单,我们只需要借助一个模块即可完成,这个模块就是”fail”模块。

我们知道,在执行playbook时,如果playbook中的任何一个任务执行失败,playbook都会停止运行,除非这个任务设置了”ignore_errors: true”,在任务没有设置”ignore_errors: true”的情况下,任务执行失败后,playbook就会自动终止,而fail模块天生就是一个用来”执行失败”的模块,当fail模块执行后,playbook就会认为有任务失败了,从而终止运行,实现我们想要的中断效果,来看一个小示例:

[root@server4 ~]# vim block4.yml
[root@server4 ~]# cat block4.yml 
---
- hosts: testB
  remote_user: root
  tasks:
  - debug:
      msg: "1"
  - debug:
      msg: "2"
  - fail:
  - debug:
      msg: "3"
  - debug:
      msg: "4"

如上例所示,上例playbook中一共有4个debug任务,在第2个debug任务之后,我们调用了fail模块,那么我们来运行一下上例playbook,执行后输出信息如下
在这里插入图片描述

从上图可以看出,当前两个debug模块输出了对应的信息后,playbook报错了,之后的debug模块并未被调用,实现了中断剧本运行的效果,当执行fail模块时,fail模块默认的输出信息为’Failed as requested from task’,我们可以通过fail模块的msg参数自定义报错的信息,示例如下
[root@server4 ~]# vim block5.yml

[root@server4 ~]# cat block5.yml 
---
- hosts: testB
  remote_user: root
  tasks:
  - debug:
      msg: "1"
  - fail:
      msg: "Interrupt running playbook"
  - debug:
      msg: "2"

在这里插入图片描述

当然,上述示例只是为了初步介绍fail模块的用法,我们通常并不会毫无理由的想要去中断playbook,通常需要对某些条件进行判断,如果条件满足,则中断剧本,所以,fail模块通常与when结合使用,比如,如果之前模块执行后的标准输出信息中包含字符串’error’,则认为中断剧本的条件成立,就立即调用fail模块,以终断playbook,示例如下:

[root@server4 ~]# vim fail1.yml 
[root@server4 ~]# cat fail1.yml 
---
- hosts: testB
  remote_user: root
  tasks:
  - shell: "echo 'This is a string for testing--error'"
    register: return_value
  - fail:
      msg: "Conditions established,Interrupt running playbook"
    when: "'error' in return_value.stdout"
  - debug:
      msg: "I never execute,Because the playbook has stopped"

在这里插入图片描述
上例中,我们使用shell模块故意输出了一个包含’error’字符串的文本,并且将shell模块执行后的返回值注册到了变量’ return_value’中,在之后调用了fail模块,并对fail模块添加了判断条件,对应的条件为 “‘error’ in return_value.stdout”,这个条件表示shell模块执行后的标注输出信息中如果包含’error’字符串,则条件成立,其中,’in’关键字的用法与 python 中’in’的用法相同,可以使用’in’关键字判断一个字符串是否存在于另一个字符串中,也可以用于判断一个特定的值是否存在于列表中,由于shell标准输出的信息中的确包含error字符串,所以fail模块对应的条件成立,最终调用fail模块,playbook终止运行。

不过需要注意的是,当使用”in”或者”not in”进行条件判断时,整个条件需要用引号引起,并且,需要判断的字符串也需要使用引号引起,所以,使用’in’或者’not in’进行条件判断时,如下两种语法是正确的:

when: ' "successful" not in return_value.stdout '
when: " 'successful' not in return_value.stdout "

 

Tags: