when
在ansible中,條件判斷的關鍵詞是when
---
- hosts: all
remote_user: root
tasks:
- debug:
msg: "System release is centos"
when: ansible_distribution == "CentOS"

ansible_distribution就是facts信息中的一個key,之前如果我們需要引用變量一般是通過"{{ key }}"這樣的方式獲取,但是在when關鍵詞中,不需要添加"{{ }}"。
---
- hosts: all
remote_user: root
gather_facts: no
tasks:
- debug:
msg: "{{ item }}"
with_items:
- 1
- 2
- 3
when: item > 1


下面是一個邏輯運算實例
---
- hosts: all
remote_user: root
tasks:
- debug:
msg: "System release is centos7"
when: ansible_distribution == "CentOS" and ansible_distribution_major_version == "7"
邏輯與除了and 也可以使用列表的方式表示。
---
- hosts: all
remote_user: root
tasks:
- 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: all
remote_user: root
tasks:
- debug:
msg: "1"
- debug:
msg: "2"
- fail:
- debug:
msg: "3"
- debug:
msg: "4"

我們也可以通過fail模塊自帶的msg,自定義報錯信息,
---
- hosts: test70
remote_user: root
tasks:
- debug:
msg: "1"
- fail:
msg: "Interrupt running playbook"
- debug:
msg: "2"

fail+when
fail模塊通常與when模塊結合,如果中斷劇本的條件成立,則執行fail模塊,中斷劇本。
---
- hosts: all
remote_user: root
tasks:
- 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: all
remote_user: root
tasks:
- debug:
msg: "I execute normally"
- shell: "echo 'This is a string for testing error'"
register: return_value
failed_when: ' "error" in return_value.stdout'
- debug:
msg: "I never execute,Because the playbook has stopped"

changed_when
failed_when關鍵詞的作用是在條件成立時將任務狀態改為失敗。
changed_when關鍵詞的作用是在條件成立時,將任務狀態改為changed。
---
- hosts: all
remote_user: root
tasks:
- debug:
msg: "test message"
changed_when: 2 > 1

當changed_when狀態被設置為false時,不管原任務狀態為啥,最終都會被設置為ok狀態
---
- hosts: all
remote_user: root
tasks:
- shell: "ls /opt"
changed_when: True

