Home > other >  Iterate over a dictionary with multiple values in Ansible
Iterate over a dictionary with multiple values in Ansible

Time:04-29

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

CodePudding user response:

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}
  • Related