天天看點

Ansible Conditionals

 一、條件語句

    條件判斷語句,就是根據某些變量的值來控制Ansible的執行流程。控制某些主機執行某些操作與不執行某些操作。根據某些操作結果,判斷是否執行其它操作等等。

    Ansible的條件判斷語句隻有 when 語句,結合變量使用才能顯示出它的價值。when的用法:在想要進行判斷的語句下面添加when語句即可進行條件判斷.

二、示例

支援判斷的操作符

1、比較操作符

       ==       !=       >       >=       <       <=

2、邏輯運算符

       and       or       not

tasks:                #簡單的判斷
   - name: "shutdown Debian flavored systems"
     command: /sbin/shutdown -t now
     when: ansible_os_family == "Debian"      
tasks:                 #組合形式的判斷
  - name: "shutdown CentOS 6 and Debian 7 systems"
    command: /sbin/shutdown -t now    
    when: (ansible_distribution == "CentOS" and ansible_distribution_major_version == "6") or
          (ansible_distribution == "Debian" and ansible_distribution_major_version == "7")      
tasks:                   #基于某些task的結果,執行相應的task
  - command: /bin/false
    register: result   
    ignore_errors: True
  - command: /bin/something
    when: result|failed
  - command: /bin/something_else
    when: result|success
  - command: /bin/still/something_else
    when: result|skipped      
tasks:                      #如果一些變量沒有定義,可以使用Jinja2的define測試。,來執行一些操作
    - 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 undefined      
tasks:               #有時一些變量的傳回結果是字元串,但是你想對它做一些數學運算
  - shell: echo "only on Red Hat 6, derivatives, and later"
    when: ansible_os_family == "RedHat" and ansible_lsb.major_release|int >= 6      
---              #對是否執行一些外部任務進行條件判斷
- hosts: local
  vars:
   test: true
 
  tasks:
  - name: Test test
    debug: msg="Hello When"
    when: test
 
  - include: pre.yml         #根據條件判斷,是否include某個外部任務檔案。
    when: test           
 
  roles:
    - { role: /home/aheahe/roles/test, when: test }   #結合條件判斷,是否加載某個Role      
上一篇: Ansible入門
下一篇: ansible安裝

繼續閱讀