Ansible
當所有主機上的任務都失敗時,Ansible 全域失敗消息
當所有主機上的任務都失敗時,我需要一條失敗消息。例如:
- ios_facts: gather_subset: min failed_when: "{{ ansible_net_hostname }} contains 123"
其中所有主機名都包含 123,因此它會觸發失敗任務
- fail: msg: all of the hostnames contains 123 when: xxxxx
例如,給定用於測試的庫存
shell> cat hosts host1 ansible_net_hostname=host_123_A host2 ansible_net_hostname=host_123_B host3 ansible_net_hostname=host_123_C
下面的播放顯示瞭如何找到列表
- hosts: all gather_facts: false tasks: - debug: var: ansible_net_hostname - debug: msg: | All names: {{ _names }} Search names: {{ _search }} vars: _names: "{{ hostvars|json_query('*.ansible_net_hostname') }}" _search: "{{ _names|select('search', '123')|list }}" run_once: true
給
TASK [debug] *********************************************************** ok: [host1] => ansible_net_hostname: host_123_A ok: [host2] => ansible_net_hostname: host_123_B ok: [host3] => ansible_net_hostname: host_123_C TASK [debug] *********************************************************** ok: [host1] => msg: |- All names: ['host_123_A', 'host_123_B', 'host_123_C'] Search names: ['host_123_A', 'host_123_B', 'host_123_C']
比較列表的長度
- debug: msg: all of the hostnames contains 123 vars: _names: "{{ hostvars|json_query('*.ansible_net_hostname') }}" _search: "{{ _names|select('search', '123')|list }}" when: _names|length == _search|length run_once: true
(信用@Zeitounator 指向這個選項。)
如果您以清單中的所有主機為目標,則上述查詢有效。如果您想定位一組主機,請使用特殊變數ansible_play_hosts_all並從hostvars中提取變數。例如,給定庫存
shell> cat hosts [test_123] host[0001:1024] [test_123:vars] ansible_net_hostname=host_123_A
表演
- hosts: test_123 gather_facts: false tasks: - debug: msg: | All names: {{ _names|length }} Search names: {{ _search|length }} vars: _names: "{{ ansible_play_hosts_all| map('extract', hostvars, 'ansible_net_hostname')| list }}" _search: "{{ _names|select('search', '123')|list }}" run_once: true
給
TASK [debug] ***************************************************** ok: [host0001] => msg: |- All names: 1024 Search names: 1024
要評估條件,請像以前一樣比較列表的長度。