Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through a list of dictionary, and print out every key and value pair in Ansible

Tags:

python

ansible

I have an list of dictionary in Ansible config

myList
    - name: Bob
      age: 25
    - name: Alice
      age: 18
      address: USA

I write code as

- name: loop through
  debug: msg ="{{item.key}}:{{item.value}}"
  with_items: "{{ myList }}"

I want to print out like

msg: "name:Bob age:25 name:Alice age:18 address:USA"

How can I loop through this dictionary and get key and value pairs? Because it don't know what is the key. If I change as {{ item.name }}, ansible will work, but I also want to know key

like image 484
Neil Avatar asked Sep 14 '16 18:09

Neil


1 Answers

If you want to loop through the list and parse every item separately:

- debug: msg="{{ item | dictsort | map('join',':') | join(' ') }}"
  with_items: "{{ myList }}"

Will print:

"msg": "age:25 name:Bob"
"msg": "address:USA age:18 name:Alice"

If you want to join everything into one line, use:

- debug: msg="{{ myList | map('dictsort') | sum(start=[]) | map('join',':') | join(' ') }}"

This will give:

"msg": "age:25 name:Bob address:USA age:18 name:Alice"

Keep in mind that dicts are not sorted in Python, so you generally can't expect your items to be in the same order as in yaml-file. In my example, they are sorted by key name after dictsort filter.

like image 100
Konstantin Suvorov Avatar answered Oct 28 '22 14:10

Konstantin Suvorov