Ansible-----條件判斷與錯誤處理
阿新 • • 發佈:2019-04-04
-- con top remote 失敗 分享圖片 自帶 ask mes
fail模塊
想要playbook按照我們的意願中斷任務,可以借助fail模塊。
在任務沒有設置ignore_errors:true情況下,如果有任務執行失敗,playbook會自動停止執行,當fail模塊執行後,playbook會認為任務執行失敗了,會主動中止任務。
--- - hosts: all remote_user: root tasks: - debug: msg: "1" - debug: msg: "2" - fail: - debug: msg: "3" - debug: msg: "4"
我們也可以通過fail模塊自帶的msg,自定義報錯信息,
--- - hosts: test70 remote_user: root tasks: - debug: msg: "1" - fail: msg: "Interrupt running playbook" - debug: msg: "2"
fail+when
fail模塊通常與when模塊結合,如果中斷劇本的條件成立,則執行fail模塊,中斷劇本。
--- - hosts: all 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"
failed_when也可以完成類似的功能,當條件成立時將對應任務的狀態設置為失敗,中止劇本。
--- - hosts: all remote_user: root tasks: - debug: msg: "I execute normally" - shell: "echo ‘This is a string for testing error‘" register: return_value failed_when: ‘ "error" in return_value.stdout‘ - debug: msg: "I never execute,Because the playbook has stopped"
changed_when
failed_when關鍵詞的作用是在條件成立時將任務狀態改為失敗。
changed_when關鍵詞的作用是在條件成立時,將任務狀態改為changed。
--- - hosts: all remote_user: root tasks: - debug: msg: "test message" changed_when: 2 > 1
當changed_when狀態被設置為false時,不管原任務狀態為啥,最終都會被設置為ok狀態
--- - hosts: all remote_user: root tasks: - shell: "ls /opt" changed_when: True
Ansible-----條件判斷與錯誤處理