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]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章