find element with dictionary in Ansible and return value

1,731 views
Skip to first unread message

maulik patel

unread,
Jul 20, 2022, 6:32:40 AM7/20/22
to Ansible Project
hi ,

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': 

Abhijeet Kasurde

unread,
Jul 21, 2022, 10:10:21 AM7/21/22
to ansible...@googlegroups.com
The last task should be -

```
- debug:
msg: "{{ sites[site] }}"
when: "site in sites.keys()"

--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/10a24e20-5399-46bf-9187-ac55ad2f4496n%40googlegroups.com.


--
Thanks,
Abhijeet Kasurde

Brian Coca

unread,
Jul 21, 2022, 10:26:08 AM7/21/22
to Ansible Project
First you conflate site as both a variable and a string, showing both
examples below to make the distinction clear.

You don't need key/keys() nor quotes if 'site' is a variable

when: site in sites

You seem to use site as both var and string, if site is a string, you
need quotes

when: "'site' in sites"

also you can do this

msg: "{{ sites.get(site)}}" if variable or msg: "{{
sites.get('site')}}" if string

Avoids error and shows 'none' if missing.


--
----------
Brian Coca

Reply all
Reply to author
Forward
0 new messages