Ansible: Generate List of Dictionaries

Let’s put the band back together! Here is a quick way of merging two lists into a list of dictionaries. The two lists (names, instruments) are merged with the with_together loop, which is similar to Python’s zip() function.

When setting the fact, make sure that the fact name (band) is the same as the list name of the dictionary.

---
- hosts: my_host
  gather_facts: no
  vars:
    names: ["Miles","Sonny","Red","Paul","Philly"]
    instruments: ["Trumpet","Saxophone","Piano","Bass","Drums"]
  tasks:
    - set_fact:
        band: "{{ band|default([]) + [ {'name': item.0, 'instrument': item.1} ] }}"
      with_together:
        - "{{ names }}"
        - "{{ instruments }}"

    - debug: var=band
    
TASK [debug] **********************************************************************
ok: [my_host] => {
    "band": [
        {
            "instrument": "Trumpet",
            "name": "Miles"
        },
        {
            "instrument": "Saxophone",
            "name": "Sonny"
        },
        {
            "instrument": "Piano",
            "name": "Red"
        },
        {
            "instrument": "Bass",
            "name": "Paul"
        },
        {
            "instrument": "Drums",
            "name": "Philly"
        }
    ]
}

Leave a Reply

Your email address will not be published. Required fields are marked *