Ansible, with_nested, How to asign dynamic variables in loop

Solution 1:

A: For example, the task below

- debug:
    msg: "{{ item.0.team_name }}: {{ item.1.name }}: {{ index1|int + 1 }}"
  with_subelements:
    - "{{ teams }}"
    - applications
  vars:
    team_names: "{{ teams|
                    map(attribute='team_name')|
                    list }}"
    index0: "{{ team_names.index(item.0.team_name) }}"
    applications: "{{ teams|
                      map(attribute='applications')|
                      list }}"
    application_names: "{{ applications[index0|int]|
                           map(attribute='name')|
                           list }}"
    index1: "{{ application_names.index(item.1.name) }}"

gives

  msg: 'Name-of-Team_A: app_name_a: 1'
  msg: 'Name-of-Team_A: app_name_b: 2'
  msg: 'Name-of-Team_B: app_name_c: 1'
  msg: 'Name-of-Team_B: app_name_d: 2'

This solution is limited to unique lists.


A better structure for this use-case is a dictionary. For example, the task below gives the same results

- debug:
    msg: "{{ item.0.key }}: {{ item.1 }}: {{ teams[item.0.key].index(item.1) + 1 }}"
  with_subelements:
    - "{{ teams|dict2items }}"
    - value
  vars:
    teams:
      Name-of-Team_A:
        - app_name_a
        - app_name_b
      Name-of-Team_B:
        - app_name_c
        - app_name_d

The lists must be unique. The method index will find the first match.