Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search Dictionary Values in Ansible

Having a dictionary like this:

ossec_datacenter:
  atlanta:
    hostname: 'server1.fakedomain.net'
    ip: '192.168.12.170'
    port: '1515'
  miami:
    hostname: 'server2.fakedomain.net'
    ip: '192.168.20.31'
    port: '1514'
  dallas:
    hostname: 'server2.fakedomain.net'
    ip: '192.168.20.20'
    port: '1515'

How would I search for all values in this dictionary in my when clause?

I can access variables using ossec_datacenter[ossec_dc]['hostname']

But I want so search all values to make sure no matches are present.

In other words I don't want the inventory_hostname nor the IP to be found anywhere in that data structure.

like image 503
Simply Seth Avatar asked Nov 26 '25 14:11

Simply Seth


1 Answers

If you want to use json_query (requires ansible 2.2) you can do this to search ip and hostname:

    - name: find inventory_hostname
      set_fact:
        found: True
      with_items:
        - "{{ ossec_datacenter | json_query('*.ip') }}"
        - "{{ ossec_datacenter | json_query('*.hostname') }}"
      when: "inventory_hostname == item"

or if you want to search any of the keys in the datacenters (ip, hostname, or port):

- name: find inventory_hostname
  set_fact:
    found: True
  with_items: "{{ ossec_datacenter | json_query('*.*') }}"
  when: "inventory_hostname == item"

and then test the found var.

like image 77
Rob H Avatar answered Nov 28 '25 05:11

Rob H



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!