簡體   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