繁体   English   中英

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

[英]Iterate over a dictionary with multiple values in Ansible

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

输入.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

当前 Output

[
    {
        "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"
        ]
    }
]

预计 Output

[
    {
        "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}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM