简体   繁体   中英

Iterate over a dictionary with multiple values in Ansible

Here i would like to iterate through the dictionary(Input.yml) with multiple values and build a JSON as mentioned in the expected output. There are 2 keys(Internal & External) with multiple values, i even have tried some solutions ( Iterate dict Ansible, each key multiple values ), but fail to get a proper result.

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"

Playbook

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

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

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

For example

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

gives

  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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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