Search Dictionary Values in Ansible

白昼怎懂夜的黑 提交于 2019-12-24 01:03:53

问题


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.


回答1:


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.




回答2:


Here's a condition for hostname:

when: inventory_hostname not in (ossec_datacenter.values() | map(attribute='hostname') | list)

Use ansible_default_ipv4.address or some other fact about IP address and reduce your dict with map(attribute='ip') to search for IP addresses.



来源:https://stackoverflow.com/questions/41581273/search-dictionary-values-in-ansible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!