printing the items on dictionary format

39 views
Skip to first unread message

Veera

unread,
Mar 14, 2023, 8:58:27 AM3/14/23
to Ansible Project
I have the items defined in  the file  vars/myvars.yml as below:

world:
     asia:
         country:  india
         state:     maha         
         city:        mumbai
         
     n_america:
           nation:  canada
           province : quebec
           city:  montreal

When I try to  print them with a loop and subelements , i am missing something 
     - name:  play to print the details
       hosts: localhost
       gather_facts: no
       vars: 
            - vars/myvars.yml
       tasks:
           - name: printing the details of montreal
              debug:
                  msg: "{{  item[2] ['city']}}"
               loop: "{{   world | subelements('n_america') | dict2items   }}"

I receive a error like      "obj must be a list of dicts or a nested dict"}
                    

msg: with "world .n_america.city" will work 
I want to print this through loop only , as i need to process other items  also.

Thanks ,, 
  

Avinash Jadhav

unread,
Mar 14, 2023, 9:09:53 AM3/14/23
to ansible...@googlegroups.com
Hi 
  you can try this way 
 

- name: printing the details of montreal
  debug:
    msg: "{{ item.value.city }}"

Veera

unread,
Mar 14, 2023, 9:30:44 AM3/14/23
to Ansible Project
Thanks .. You mean with the "loop" enabled .. It did not work in both modes.

I am looking for a way so that this particular play will process  the variables(items) under n_america   in 
vars_files : 
    - vars/myvars.yml

Todd Lewis

unread,
Mar 14, 2023, 2:33:29 PM3/14/23
to Ansible Project
Not sure what you're trying to do with subelements.
You could do this:
---
- name: Print world details

  hosts: localhost
  gather_facts: no
  vars:
    world:
      asia:
        country: india
        state:   maha
        city:    mumbai
      n_america:
        nation:   canada
        province: quebec
        city:     montreal
  tasks:
    - name: Printing details of montreal
      ansible.builtin.debug:
        msg: "{{ item.value.city | default(item.key ~ ' has no city') }}"
      loop: "{{ world | dict2items }}"
      when: item.key == 'n_america'

Veera

unread,
Mar 16, 2023, 2:05:40 PM3/16/23
to Ansible Project
Thanks Todd,

It works . 

"Not sure what you're trying to do with subelements."   -  I want to avoid  printing messages of  other dict items ( asia) from vars  during the execution (in the  skipping), which prints some sensitive info on the screen.  
Turning on no_log  is not helpful in registering the output.
So , I was trying to call only the variables under n_america when I  execute the task  and i got it .  However for now skipping shows the items from asia during the play .

Reply all
Reply to author
Forward
0 new messages