Find element with dictionary in Ansible and return value

Viewed 33

i'm trying to value of one yaml file1 with another file2 which has list of dict and if element if file1 matched with key/value of file2 then need to use value of file1 need to use as a key of file2 and return value of it...

not sure how we can leverage "when" condition or might any other way around it...

file1.yaml:

  site: CL1

file2.yaml:

site_int:
  -
    CL1:
      as: 6500X
      int: ethernet1/1
      peer_ip: X.X.X.X/X
    EL1:
      as: 65063
      int: loopback.66
      peer_ip: Y.Y.Y.Y/Y

playbook:

- name: site_facts
           set_fact:
                   sites: "{{item}}"
           loop: "{{ site_int) }}"


         - name: debug
           debug:
                   msg: "{{sites['site']}}"
           when: "site in sites.key"

error:

fatal: [CL1]: FAILED! => {"msg": "The conditional check 'site in sites.key()' failed. The error was: error while evaluating conditional (site in sites.key()): 'dict object' has no attribute 'key'\n\nThe error appears to be in '/etc/ansible/aws/test_site.yaml':

1 Answers

For example,

  sites: "{{ site_int|map('dict2items')|
                      map('selectattr', 'key', 'eq', site)|
                      flatten|items2dict }}"

gives

  sites:
    CL1:
      as: 6500X
      int: ethernet1/1
      peer_ip: X.X.X.X/X

Example of a complete playbook

- hosts: localhost
  vars_files:
    - file1.yaml
    - file2.yaml
  vars:
    sites: "{{ site_int|map('dict2items')|
                        map('selectattr', 'key', 'eq', site)|
                        flatten|items2dict }}"
  tasks:
    - debug:
        msg: |-
          sites.{{ site }}:
            {{ sites[site]|to_nice_yaml|indent(2) }}

gives

  msg: |-
    sites.CL1:
      as: 6500X
      int: ethernet1/1
      peer_ip: X.X.X.X/X
Related