How do you loop over a list of dictionaries, for example users that each need their own group?
Each list element is a dictionary, so item is a whole dictionary on every pass and you read its fields with item['name'], item['groups'], and so on.
* On each pass, item is one whole dictionary; its keys fill different module arguments. *
A flat list can only vary one value per pass. When each pass needs several related values (a user name and that user's group), make every element a dictionary:
- name: Users exist and are in the correct groups
ansible.builtin.user:
name: "{{ item['name'] }}"
state: present
groups: "{{ item['groups'] }}"
loop:
- name: jane
groups: wheel
- name: joe
groups: root
Result: user jane exists and is in group wheel; user joe exists and is in group root. The values that belong together stay together in one element, so they can't get out of step the way two parallel lists could.
item.name (dot notation) works too, but bracket notation is safer: it can't collide with a Python method name such as items or keys.
Go deeper:
Loops: iterating over a list of hashes (official docs) โ the same pattern with more fields.