Ansible Generate List of Compliying hosts

Viewed 47

I'm trying to generate a list with the information of hosts that match a certain condition (for instance, that NTP is synched for an inventory of Cisco devices). So that the ones matching that condition will be added to a list with say hostname and IP, for later generating a CSV.

Checking the condition is quite easy, but I'm struggling on how to generate this list.

  • Adding them to a list in a var doesn't seem wise, as it requires of serial execution of tasks per device.
  • Should I set a boolean fact for each device (i.e., ntp_synched, and then generate a list with the ansible_net_hostname and ansible_host of each device? How to do this?
    - 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]'
1 Answers

For example, given the inventory for testing

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

Create the dictionary of the hosts and statuses

- 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

gives

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

List the synchronized hosts

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

gives

  msg:
  - host01
  - host02
Related