![当任务在所有主机上失败时,Ansible 全局失败消息](https://linux22.com/image/773741/%E5%BD%93%E4%BB%BB%E5%8A%A1%E5%9C%A8%E6%89%80%E6%9C%89%E4%B8%BB%E6%9C%BA%E4%B8%8A%E5%A4%B1%E8%B4%A5%E6%97%B6%EF%BC%8CAnsible%20%E5%85%A8%E5%B1%80%E5%A4%B1%E8%B4%A5%E6%B6%88%E6%81%AF.png)
当任务在所有主机上失败时,我需要一条失败消息。例如:
- ios_facts:
gather_subset: min
failed_when: "{{ ansible_net_hostname }} contains 123"
所有主机名都包含 123,因此会触发失败任务
- fail:
msg: all of the hostnames contains 123
when: xxxxx
答案1
例如,给定测试库存
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和提炼来自的变量主机变量。例如,给定库存
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
要评估条件,请像以前一样比较列表的长度。