Ansible-----条件判断与错误处理
when
在ansible中,條件判斷的關(guān)鍵詞是when
--- - hosts: allremote_user: roottasks:- debug:msg: "System release is centos"when: ansible_distribution == "CentOS"ansible_distribution就是facts信息中的一個(gè)key,之前如果我們需要引用變量一般是通過"{{ key }}"這樣的方式獲取,但是在when關(guān)鍵詞中,不需要添加"{{? }}"。
--- - hosts: allremote_user: rootgather_facts: notasks:- debug:msg: "{{ item }}"with_items:- 1- 2- 3when: item > 1下面是一個(gè)邏輯運(yùn)算實(shí)例
--- - 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"這個(gè)列表中的每一項(xiàng)都是一個(gè)條件,當(dāng)所有條件同時(shí)成立時(shí),任務(wù)才會(huì)執(zhí)行。
fail模塊
想要playbook按照我們的意愿中斷任務(wù),可以借助fail模塊。
在任務(wù)沒有設(shè)置ignore_errors:true情況下,如果有任務(wù)執(zhí)行失敗,playbook會(huì)自動(dòng)停止執(zhí)行,當(dāng)fail模塊執(zhí)行后,playbook會(huì)認(rèn)為任務(wù)執(zhí)行失敗了,會(huì)主動(dòng)中止任務(wù)。
--- - hosts: allremote_user: roottasks:- debug:msg: "1"- debug:msg: "2"- fail:- debug:msg: "3"- debug:msg: "4"我們也可以通過fail模塊自帶的msg,自定義報(bào)錯(cuò)信息,
--- - hosts: test70remote_user: roottasks:- debug:msg: "1"- fail:msg: "Interrupt running playbook"- debug:msg: "2"fail+when
?fail模塊通常與when模塊結(jié)合,如果中斷劇本的條件成立,則執(zhí)行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也可以完成類似的功能,當(dāng)條件成立時(shí)將對(duì)應(yīng)任務(wù)的狀態(tài)設(shè)置為失敗,中止劇本。
--- - 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關(guān)鍵詞的作用是在條件成立時(shí)將任務(wù)狀態(tài)改為失敗。
changed_when關(guān)鍵詞的作用是在條件成立時(shí),將任務(wù)狀態(tài)改為changed。
--- - hosts: allremote_user: roottasks:- debug:msg: "test message"changed_when: 2 > 1?當(dāng)changed_when狀態(tài)被設(shè)置為false時(shí),不管原任務(wù)狀態(tài)為啥,最終都會(huì)被設(shè)置為ok狀態(tài)
--- - hosts: allremote_user: roottasks:- shell: "ls /opt"changed_when: True?
轉(zhuǎn)載于:https://www.cnblogs.com/jinyuanliu/p/10656467.html
總結(jié)
以上是生活随笔為你收集整理的Ansible-----条件判断与错误处理的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Appium环境搭建-完整版
- 下一篇: 题解 P5259【欧稳欧再次学车】