Ansible: processing data structures with Jinja2

Sometimes, you need to switch keys and values of a supplied dictionary or an array.

You can process this data structure to create another variable that can simplify your code.

For instance, we have a list of motocycles with an associated color (in real life, you may get the list of all your loadbalancers in AWS).

- hosts: localhost
  gather_facts: no
  vars:
     dico: [
            { keyone: "ducati",
              keytwo: "red"
            },
            { keyone: "kawazaki",
              keytwo: "green"
            },
            { keyone: "honda",
              keytwo: "blue"
            }
           ]

# Now, you process with Jinja and store the result in a fact
# fact is stored in localhost's facts
  tasks:
    - set_fact :
       sf_new_dict: |
        {% set comma = joiner(",") %}
        { {% for item in dico -%}
          {{ comma() }} '{{item.keytwo}}':'{{item.keyone}}'
        {%- endfor %}
        }

    - debug: var=sf_new_dict
    # then you can access directly the record you need
    - debug: msg="who sells red bikes ? {{hostvars['localhost'].sf_new_dict['red']}}"

Let’s give a run !

TASK [set_fact] ************************************************************
ok: [localhost]

TASK [debug] ***************************************************************
ok: [localhost] => {
    "sf_new_dict": {
        "blue": "honda",
        "green": "kawazaki",
        "red": "ducati"
    }
}

TASK [debug] *****************************************************************
ok: [localhost] => {
    "msg": "who sells red bikes ?  ducati"
}