循环遍历两个字典列表的乘积(Ansible / Jinja2)

循环遍历两个字典列表的乘积(Ansible / Jinja2)

我有两个字典列表,想将笛卡尔积作为一个列表循环。我该怎么做?

样本数据:

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

期望结果:

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}
      ]

我尝试过一种表达方式"{{ environments|product(colorscheme)|list }}",虽然接近我想要的但还不完全是我想要的。

表达结果:

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}
        ]
      ]

答案1

这是您可以采取的一种方法。不确定这是否是最好的方法。

- 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"
#         }
#     ]
# }
#

相关内容