Ansible-----条件判断与错误处理
when
在ansible中,條件判斷的關鍵詞是when
--- - hosts: allremote_user: roottasks:- debug:msg: "System release is centos"when: ansible_distribution == "CentOS"ansible_distribution就是facts信息中的一個key,之前如果我們需要引用變量一般是通過"{{ key }}"這樣的方式獲取,但是在when關鍵詞中,不需要添加"{{? }}"。
--- - hosts: allremote_user: rootgather_facts: notasks:- debug:msg: "{{ item }}"with_items:- 1- 2- 3when: item > 1下面是一個邏輯運算實例
--- - hosts: allremote_user: roottasks:- debug:msg: "System release is centos7"when: ansible_distribution == "CentOS" and ansible_distribution_major_version == "7"邏輯與除了and 也可以使用列表的方式表示。
--- - hosts: allremote_user: roottasks:- debug:msg: "System release is centos7"when:- ansible_distribution == "CentOS"- ansible_distribution_major_version == "7"這個列表中的每一項都是一個條件,當所有條件同時成立時,任務才會執行。
fail模塊
想要playbook按照我們的意愿中斷任務,可以借助fail模塊。
在任務沒有設置ignore_errors:true情況下,如果有任務執行失敗,playbook會自動停止執行,當fail模塊執行后,playbook會認為任務執行失敗了,會主動中止任務。
--- - hosts: allremote_user: roottasks:- debug:msg: "1"- debug:msg: "2"- fail:- debug:msg: "3"- debug:msg: "4"我們也可以通過fail模塊自帶的msg,自定義報錯信息,
--- - hosts: test70remote_user: roottasks:- debug:msg: "1"- fail:msg: "Interrupt running playbook"- debug:msg: "2"fail+when
?fail模塊通常與when模塊結合,如果中斷劇本的條件成立,則執行fail模塊,中斷劇本。
--- - hosts: allremote_user: roottasks:- 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: allremote_user: roottasks:- debug:msg: "I execute normally"- shell: "echo 'This is a string for testing error'"register: return_valuefailed_when: ' "error" in return_value.stdout'- debug:msg: "I never execute,Because the playbook has stopped"changed_when
failed_when關鍵詞的作用是在條件成立時將任務狀態改為失敗。
changed_when關鍵詞的作用是在條件成立時,將任務狀態改為changed。
--- - hosts: allremote_user: roottasks:- debug:msg: "test message"changed_when: 2 > 1?當changed_when狀態被設置為false時,不管原任務狀態為啥,最終都會被設置為ok狀態
--- - hosts: allremote_user: roottasks:- shell: "ls /opt"changed_when: True?
轉載于:https://www.cnblogs.com/jinyuanliu/p/10656467.html
總結
以上是生活随笔為你收集整理的Ansible-----条件判断与错误处理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Appium环境搭建-完整版
- 下一篇: 题解 P5259【欧稳欧再次学车】