在 Ansible 中迭代具有多个值的字典

Iterate over a dictionary with multiple values in Ansible

在这里,我想用多个值遍历字典 (Input.yml) 并构建一个 JSON,如预期输出中所述。有 2 个键(内部和外部)具有多个值,我什至尝试了一些解决方案(),但未能得到正确的结果。

Input.yml

StaticRoutes:        
         - Internal:
               - "1.1.1.1/8"
               - "2.2.2.2/16"
         - External:
               - "5.5.5.1"
               - "5.5.5.2"

gateway:
         - "6.6.6.6"

剧本

- name: Create route table
      set_fact:
        route: >-
         {{
            route | default([]) + 
            [{  'name': item.key ,
                'subnet':  item.value,
                'gatewayIP': gateway.0}]
         }}
      with_dict: "{{ StaticRoutes}}"     
      ignore_errors: yes

当前输出

[
    {
        "gatewayIP": "6.6.6.6",
        "name": "Internal",
        "subnet": [
            "1.1.1.1/8",
            "2.2.2.2/16"
        ]
    },
    {
        "gatewayIP": "10.147.166.1",
        "name": "External",
        "subnet": [
            "5.5.5.1",
            "5.5.5.2"
        ]
    }
]

预期输出

[
    {
        "gatewayIP": "6.6.6.6",
        "name": "Internal",
        "subnet": "1.1.1.1/8"
    },
    {
        "gatewayIP": "6.6.6.6",
        "name": "Internal",
        "subnet": "2.2.2.2/16"
    },
    {
        "gatewayIP": "6.6.6.6",
        "name": "External",
        "subnet":"5.5.5.1"  
    },
    {
        "gatewayIP": "6.6.6.6",
        "name": "External",
        "subnet": "5.5.5.2"
    } 
]

例如

    - set_fact:
        route: "{{ route|default([]) + [{'name': item.0.key,
                                         'subnet': item.1,
                                         'gatewayIP': gateway.0}] }}"
      with_subelements:
        - "{{ StaticRoutes|map('dict2items')|flatten }}"
        - value

给予

  route:
    - {gatewayIP: 6.6.6.6, name: Internal, subnet: 1.1.1.1/8}
    - {gatewayIP: 6.6.6.6, name: Internal, subnet: 2.2.2.2/16}
    - {gatewayIP: 6.6.6.6, name: External, subnet: 5.5.5.1}
    - {gatewayIP: 6.6.6.6, name: External, subnet: 5.5.5.2}