ansible之條件語句when


注冊變量:

變量的另一個用途是將一條命令的運行結果保存到變量中,供后面的playbook使用。例如:

- hosts: webservers

   tasks:

      - shell: /usr/bin/foo

         register: foo_result

         ignore_errors: True   使用ignore_errors來忽略錯誤信息

      - shell: /usr/bin/bar

        when: foo_result.rc == 5

 

條件語句:

在某些情況下,一個變量的值可以依賴於其他變量的值,當然也會影響Ansible的執行過程。

下面主要介紹When聲明.

  tasks:

    - name: "shutdown Debian flavored systems"

      command: /sbin/shutdown -t now

      when: ansible_os_family == "Debian"

 

下面再看一個示例,通過判斷一條命令執行結果做不同分支的二級處理。

  tasks:

    - command: /bin/false    沒有 - name 時,此行將被默認成為標題--- TASK: [command: /bin/false] 

       register: myresult

       ignore_errors: True

    - command: /bin/something

       when: myresult|failed

    - command: /bin/something_else

       when: myresult|success

    - command: /bin/still/something_else

       when: myresult|skipped

其中success為Ansible內部過濾器方法,返回True代表命令運行成功。

---------------------------------------------------------------------------

[root@localhost when]# cat main.yml
- hosts: webservers
  tasks:
   - name: haha
     command: /bin/uname
     register: result
     ignore_errors: True
   - command: /bin/df
     when: result|failed
     register: aaa
   - command: /bin/ls
     when: result|success
   - command: /bin/lsblk
     when: aaa|skipped

執行后的結果如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM