How to loop through a list of dictionary, and print out every key and value pair in Ansible
<p>I have an list of dictionary in Ansible config</p>

<pre><code>myList
    - name: Bob
      age: 25
    - name: Alice
      age: 18
      address: USA
</code></pre>

<p>I write code as</p>

<pre><code>- name: loop through
  debug: msg ="{{item.key}}:{{item.value}}"
  with_items: "{{ myList }}"
</code></pre>

<p>I want to print out like</p>

<pre><code>msg: "name:Bob age:25 name:Alice age:18 address:USA"
</code></pre>

<p>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</p>

<p>You can use a Jinja2 template:</p>

<pre><code>vars:
  myList:
    - name: Bob
      age: 25
    - name: Alice
      age: 18
      address: USA
tasks:
  - debug: msg="{% for item in myList %}{% if not loop.first %} {% endif %}{% for key, value in item.items() %}{% if not loop.first %} {% endif %}{{ key }}:{{ value}}{% endfor %}{% endfor %}";
</code></pre>

<p>Will get you:</p>

<blockquote>
  <p>"msg": "\"age:25 name:Bob age:18 name:Alice address:USA\";"</p>
</blockquote>

<p>The only problem that remains is the order of elements. I'm not sure what you can do except for naming them <code>1name</code>, <code>2age</code>, <code>3address</code> and sort them alphabetically in the <code>for</code>.</p>

python ansible