日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Ansible-----条件判断与错误处理

發布時間:2023/12/1 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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-----条件判断与错误处理的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。