Search code examples
ansibleansible-facts

Iterate ansible Loops with multiple list and map them


I can iterate the file (everything works fine using the below playbook), but I want to add a description to each VLAN using variables. So that every VLAN has a different description. The variable file:

all_vlans:
- name: DEvice1
  vlan_id:
    - 5
    - 21
    - 32 
  description: SW1
  for_serial: "OVA192FA3"
  for_host: "aoscx_1"
 
# I want something like below
- name: DEvice2
  vlan_id:
    - 11
    - 22
    - 32 
  vlan_desc:
    - VLAN_NO_11
    - VLAN_NO_22
    - VLANNO_32 
  description: SW2
  for_serial: "OVAA19FDF"
  for_host: "aoscx_2"

My playbook.

  - name: Create VLAN as Per Variables
    aoscx_vlan:
      vlan_id: "{{ item.1 }}"
      name: UPLINK_VLAN
      description: '{{ item.0.description }}'
      # admin_state: up
      state: create   #create,update,delete
    when: my_var == '{{ item.0.for_serial }}'

    loop: "{{ all_vlans|subelements('vlan_id') }}"
    loop_control:
      label: "{{ item.0.name }}"

Solution

  • If you want per-vlan descriptions, it seems simplest to restructure your data:

    all_vlans:
    - name: Device1
      vlans:
        - id: 11
          description: VLAN_NO_11
        - id: 22
          description: VLAN_NO_22
        - id: 32
          description: VLAN_NO_32
      description: SW2
      for_serial: "OVAA19FDF"
      for_host: "aoscx_2"
    

    With that, you can write:

    - name: Create VLAN as Per Variables
      aoscx_vlan:
        vlan_id: "{{ item.1.id }}"
        name: UPLINK_VLAN
        description: '{{ item.1.description }}'
        state: create
      when: my_var == item.0.for_serial
      loop: "{{ all_vlans|subelements('vlans') }}"
      loop_control:
        label: "{{ item.0.name }}"
    

    Note that I've corrected a syntax error in your when statement in the above example (you never nest {{..}} template markers inside a template, and a when statement is already an implicit Jinja template context).