Ansible9:條件陳述式【轉】

來源:互聯網
上載者:User

標籤:shell   錯誤   任務   選擇   location   基於   需要   app   匯入   

在有的時候play的結果依賴於變數、fact或者是前一個任務的執行結果,從而需要使用到條件陳述式。一、when
    有的時候在特定的主機需要跳過特定的步驟,例如在安裝包的時候,需要指定主機的作業系統類型,或者是當作業系統的硬碟滿了之後,需要清空檔案等,可以使用when語句來做判斷 。when關鍵字後面跟著的是python的運算式,在運算式中你能夠使用任何的變數或者fact,當運算式的結果返回的是false,便會跳過本次的任務

1、基本用法,樣本:

---
- name: Install VIM
 hosts: all  tasks:
   - name:Install VIM via yum
     yum: name=vim-enhanced state=installed
     when: ansible_os_family =="RedHat"
   - name:Install VIM via apt
     apt: name=vim state=installed
     when: ansible_os_family =="Debian"
   - name: Unexpected OS family
     debug: msg="OS Family {{ ansible_os_family }} is not supported" fail=yes
     when: not ansible_os_family =="RedHat" or ansible_os_family =="Debian"

    條件陳述式還有一種用法,它還可以讓你當達到一定的條件的時候暫停下來,等待你的輸入確認。一般情況下,當ansible遭遇到error時,它會直接結束運行。那其實你可以當遭遇到不是預期的情況的時候給使用pause模組,這樣可以讓使用者自己決定是否繼續運行任務:

- name: pause for unexpected conditions
 pause: prompt="Unexpected OS"
 when: ansible_os_family !="RedHat"
2、在when中使用jinja2的文法,樣本:
tasks:  - command: /bin/false    register: result        #將命令執行的結果傳遞給result變數    ignore_errors: True    #忽略錯誤  - command: /bin/something    when: result|failed    #如果註冊變數的值 是任務failed則返回true  - command: /bin/something_else    when: result|success    #如果註冊變數的值是任務success則返回true  - command: /bin/still/something_else    when: result|skipped    #如果註冊變數的值是任務skipped則返回true  - command: /bin/foo    when: result|changed    #如果註冊變數的值是任務changed則返回true
- hosts: all  user: root  vars:    epic: true  tasks:    - shell: echo "This certainly is epic!"      when: epic    - shell: echo "This certainly is not epic!"      when: not epic
4、如果變數不存在,則可以通過jinja2的‘defined‘命令跳過,樣本:

tasks:    - shell: echo "I‘ve got ‘{{ foo }}‘ and am not afraid to use it!"      when: foo is defined    - fail: msg="Bailing out. this play requires ‘bar‘"      when: bar is not defined
5、when在迴圈語句中的使用方法,樣本:
tasks:    - command: echo {{ item }}      with_items: [ 0, 2, 4, 6, 8, 10 ]      when: item > 56、在include和roles中使用when:
在include中使用的樣本:- include: tasks/sometasks.yml  when: "‘reticulating splines‘ in output"
在roles中使用的樣本:- hosts: webservers  roles:     - { role: debian_stock_config, when: ansible_os_family == ‘Debian‘ }
二、條件匯入
有些時候,你也許想在一個Playbook中以不同的方式做事,比如說在debian和centos上安裝apache,apache的包名不同,除了when語句,還可以使用下面的樣本來解決:
---- hosts: all  remote_user: root  vars_files:    - "vars/common.yml"    - [ "vars/{{ ansible_os_family }}.yml", "vars/os_defaults.yml" ]  tasks:  - name: make sure apache is running    service: name={{ apache }} state=running很多不同的yml檔案只是包含鍵和值,如下:

---# for vars/CentOS.ymlapache: httpdsomethingelse: 42

 如果作業系統是’CentOS’, Ansible匯入的第一個檔案將是’vars/CentOS.yml’,緊接著 是’/var/os_defaults.yml’,如果這個檔案不存在。而且在列表中沒有找到,就會報錯。 在Debian系統中,最先查看的將是’vars/Debian.yml’而不是’vars/CentOS.yml’, 如果沒找到,則尋找預設檔案’vars/os_defaults.yml’。 

三、with_first_found
有些時候,我們想基於不同的作業系統,選擇不同的設定檔,及設定檔的存放路徑,可以藉助with_first_found來解決:
- name: template a file   template: src={{ item }} dest=/etc/myapp/foo.conf   with_first_found:     - files:        - {{ ansible_distribution }}.conf        - default.conf       paths:        - search_location_one/somedir/        - /opt/other_location/somedir/
四、failed_when
failed_when其實是ansible的一種錯誤處理機制,是由fail模組使用了when條件陳述式的組合效果。樣本如下:
- name: this command prints FAILED when it fails  command: /usr/bin/example-command -x -y -z  register: command_result  failed_when: "‘FAILED‘ in command_result.stderr"我們也可以直接通過fail模組和when條件陳述式,寫成如下:
- name: this command prints FAILED when it fails  command: /usr/bin/example-command -x -y -z  register: command_result  ignore_errors: True- name: fail the play if the previous command did not succeed  fail: msg="the command failed"  when: "‘FAILED‘ in command_result.stderr"五、changed_when
當我們控制一些遠程主機執行某些任務時,當任務在遠程主機上成功執行,狀態發生更改時,會返回changed狀態響應,狀態未發生更改時,會返回OK狀態響應,當任務被跳過時,會返回skipped狀態響應。我們可以通過changed_when來手動更改changed響應狀態。樣本如下:

  - shell: /usr/bin/billybass --mode="take me to the river"    register: bass_result    changed_when: "bass_result.rc != 2"    #只有該條task執行以後,bass_result.rc的值不為2時,才會返回changed狀態  # this will never report ‘changed‘ status  - shell: wall ‘beep‘    changed_when: False    #當changed_when為false時,該條task在執行以後,永遠不會返回changed狀態

Ansible9:條件陳述式【轉】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.