Ansible 生成合规主机列表

Ansible Generate List of Compliying hosts

我正在尝试生成一个包含符合特定条件的主机信息的列表(例如,NTP 与 Cisco 设备清单同步)。这样符合该条件的那些将被添加到一个列表中,其中包含主机名和 IP,以便稍后生成 CSV。

检查条件很容易,但我正在为如何生成此列表而苦苦挣扎。

    - name: CHECK NTP STATUS
      ios_command:
       commands:
        - show ntp status
      register: ntp_status

    - name: NTP NOT SYNCH
      debug:
        msg: "{{ [ansible_net_hostname] }}"
      when: '"Clock is synchronized" not in ntp_status.stdout[0]'

例如,给定库存进行测试

host01 status="Clock is synchronized"
host02 status="Clock is synchronized"
host03 status="Clock is not synchronized"

创建主机和状态的字典

- hosts: all
  tasks:
    - command: "echo {{ status }}"
      register: ntp_status
    - set_fact:
        host_status: "{{ dict(_hosts|zip(_stats)) }}"
      vars:
        _hosts: "{{ ansible_play_hosts }}"
        _stats: "{{ ansible_play_hosts|
                    map('extract', hostvars, ['ntp_status','stdout'])|list }}"
      run_once: true

给予

  host_status:
    host01: Clock is synchronized
    host02: Clock is synchronized
    host03: Clock is not synchronized

列出同步的主机

    - debug:
        msg: "{{ host_status|dict2items|
                 selectattr('value', 'search', 'Clock is synchronized')|
                 map(attribute='key')|list }}"
      run_once: true

给予

  msg:
  - host01
  - host02