Ansible/Jinja2 – Loop Through Product of Two Dictionary Lists

ansible

I have two lists of dictionaries and would like to loop through the cartesian product as one. How do I do this.

sample data:

environments: [
                {title: outdoors, climate: variable},
                {title: indoors, climate: steady}
              ],
colorscheme:  [
                {top: blue, bottom: red},
                {top: pink, bottom: green}
              ]

desired result:

item: [
        {title: outdoors, climate: variable, top: blue, bottom: red},
        {title: indoors, climate: steady, top: blue, bottom: red},
        {title: outdoors, climate: variable, top: pink, bottom: green},
        {title: indoors, climate: steady, top: pink, bottom: green}
      ]

I have tried the expression "{{ environments|product(colorscheme)|list }}" which gets me close but not quite what I want.

Results of expression:

item: [
        [
          {title: outdoors, climate: variable}, 
          {top: blue, bottom: red}
        ],
        [
          {title: indoors, climate: steady},
          {top: blue, bottom: red}
        ],
        [
           {title: outdoors, climate: variable},
           {top: pink, bottom: green}
        ],
        [
           {title: indoors, climate: steady},
           {top: pink, bottom: green}
        ]
      ]

Best Answer

Here is one way you could do it. Not sure it is the best eway.

- hosts: localhost
  gather_facts: no
  vars:
    envs:
    - title: outdoors
      climate: variable
    - title: indoors
      climate: steady
    colorscheme:
    - top: blue
      bottom: red
    - top: pink
      bottom: green
  tasks:
  - debug:
      msg: >
        [
        {% for e in envs %}
        {% for c in colorscheme %}
        {{ e | combine (c) }},
        {% endfor %}
        {% endfor %}
        ]


# TASK [debug] **************************************************************************************************[3/1813$
# ok: [localhost] => {
#     "msg": [
#         {
#             "bottom": "red",
#             "climate": "variable",
#             "title": "outdoors",
#             "top": "blue"
#         },
#         {
#             "bottom": "green",
#             "climate": "variable",
#             "title": "outdoors",
#             "top": "pink"
#         },
#         {
#             "bottom": "red",
#             "climate": "steady",
#             "title": "indoors",
#             "top": "blue"
#         },
#         {
#             "bottom": "green",
#             "climate": "steady",
#             "title": "indoors",
#             "top": "pink"
#         }
#     ]
# }
#