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.
More on Jinja2, Conditionals and Loops
What role does Jinja2 play in Ansible?BeginnerWhat are the three Jinja2 delimiters?BeginnerShow a template with a loop and a conditional, and how it is deployed.BeginnerWhich filters do you use every day?BeginnerHow do you transform lists and dicts with filters (`map`, `select`, `selectattr`, `unique`, `flatten`)?IntermediateHow does `when` work and which operators can you use?Beginner