Interview Prep/Ansible/Jinja2, Conditionals and Loops

How do `subelements` and `zip` help with nested data?

AdvancedConceptJinja2, Conditionals and Loops
Answer

subelements iterates over a list of dicts and a list inside each of them, giving item.0 (parent) and item.1 (child). zip pairs lists element by element.

users:
  - name: alice
    keys: ["ssh-ed25519 AAAA...", "ssh-ed25519 BBBB..."]
tasks:
  - ansible.posix.authorized_key:
      user: "{{ item.0.name }}"
      key: "{{ item.1 }}"
    loop: "{{ users | subelements('keys') }}"

  - ansible.builtin.debug: msg="{{ item.0 }} -> {{ item.1 }}"
    loop: "{{ names | zip(ips) | list }}"

zip stops at the shortest list; use zip_longest to pad.

All Ansible questions Roadmap: Ansible

More on Jinja2, Conditionals and Loops