当任务在所有主机上失败时,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

答案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

要评估条件,请像以前一样比较列表的长度。

相关内容