Ansible—— playbook 流程控制语句

1. when条件判断

关闭掉ip地址为10.0.102.162服务器上的mysql服务,如下:

[root@test2 playbook]# cat test.yml 
---
 - hosts: all
   remote_user: root
   tasks:
     - name: shut down the db server
       service: name=mysqld state=stopped
       when: ansible_eth0.ipv4.address  == "10.0.102.162"                        #这里使用了when条件语句

2. failed_when 和changed_when

由failed_when 和changed_when来判断playbook是否运行成功和是状态是否发生改变。

---
 - hosts: localhost
  remote_user: root
  tasks:
  - name: command
    command: /bin/false
    ignore_errors: yes
  - name: another
    debug:
      msg: "this is the pring info"

这个例子中,command 命令明显就会返回一个false , 这个时候ansible-playbook就知道这个task failed,但是,有些时候,需要通过返回的字符串来判断是否failed。

- name: Fail task when the command error output prints FAILED
  command: /usr/bin/example-command -x -y -z
  register: command_result
  failed_when: "'FAILED' in command_result.stderr"

也就是说,只有在返回结果中出现字符串‘FAILED’,才认为的task 失败了
类似的有changed_when

tasks:
  - shell: /usr/bin/billybass --mode="take me to the river"
    register: bass_result
    changed_when: "bass_result.rc != 2"

  # this will never report 'changed' status
  - shell: wall 'beep'
    changed_when: False

在使用command /shell 模块的时候ansible playbook 会按照自己的判断来决定是否changed了,有时候仅仅是ls 了一下, ansible-playbook 也会认为是changed了,可能这并不是想要的,这个时候就要用例子中方法来修改task的状态了。
————Blueicex 2020/03/26 18:00 [email protected]

发布了226 篇原创文章 · 获赞 1 · 访问量 7931

猜你喜欢

转载自blog.csdn.net/blueicex2017/article/details/105123870