Loops
loop: runs a task once for each item of a list; the current item is {{ item }}. It replaces the older with_items, with_dict and friends, which still work but are not what new code should use.
Lists and lists of dictionaries
cat > loops.yml <<'YML'
- name: Loops
hosts: localhost
gather_facts: false
vars:
app_dirs: [conf, data, logs]
app_users:
- {name: deploy, shell: /bin/bash}
- {name: backup, shell: /usr/sbin/nologin}
tasks:
- name: Directories
ansible.builtin.file:
path: "app/{{ item }}"
state: directory
mode: "0755"
loop: "{{ app_dirs }}"
- name: One line per user (stand-in for the user module)
ansible.builtin.lineinfile:
path: app/conf/users
line: "{{ item.name }}:{{ item.shell }}"
create: true
mode: "0644"
loop: "{{ app_users }}"
loop_control:
label: "{{ item.name }}"
YML
ansible-playbook loops.yml | grep -E '^(ok|changed)'
cat app/conf/userschanged: [localhost] => (item=conf)
changed: [localhost] => (item=data)
changed: [localhost] => (item=logs)
changed: [localhost] => (item=deploy)
changed: [localhost] => (item=backup)
deploy:/bin/bash
backup:/usr/sbin/nologin
loop_control.label shortens what is printed per item: without it, Ansible prints the whole dictionary, which for a user with an SSH key and a password hash is long, and may print secrets.
Dictionaries: dict2items
loop needs a list. Turn a dictionary into a list of {key, value} items:
cat > dict.yml <<'YML'
- name: Loop over a dictionary
hosts: localhost
gather_facts: false
vars:
sysctl_settings:
net.ipv4.ip_forward: 0
net.ipv4.conf.all.rp_filter: 1
kernel.kptr_restrict: 2
tasks:
- name: Write a sysctl drop-in (a stand-in for ansible.posix.sysctl)
ansible.builtin.lineinfile:
path: 99-hardening.conf
regexp: "^{{ item.key }} ="
line: "{{ item.key }} = {{ item.value }}"
create: true
mode: "0644"
loop: "{{ sysctl_settings | dict2items }}"
loop_control:
label: "{{ item.key }}"
YML
ansible-playbook dict.yml | grep -E '^(ok|changed)'
cat 99-hardening.confchanged: [localhost] => (item=net.ipv4.ip_forward)
changed: [localhost] => (item=net.ipv4.conf.all.rp_filter)
changed: [localhost] => (item=kernel.kptr_restrict)
net.ipv4.ip_forward = 0
net.ipv4.conf.all.rp_filter = 1
kernel.kptr_restrict = 2
On a real server the task is ansible.posix.sysctl: {name: "{{ item.key }}", value: "{{ item.value }}", sysctl_file: /etc/sysctl.d/99-hardening.conf}, which also applies the value live; it needs root.
Registering a loop
A registered loop result holds a results list, one entry per item, each with its own item, changed, stdout…:
cat > reg.yml <<'YML'
- name: Register in a loop
hosts: localhost
gather_facts: false
tasks:
- name: Check some commands
ansible.builtin.command: "which {{ item }}"
loop: [git, jq, svn]
register: which
changed_when: false
failed_when: false
- name: Missing tools
ansible.builtin.debug:
msg: "missing: {{ which.results | rejectattr('rc', 'eq', 0) | map(attribute='item') | list }}"
YML
ansible-playbook reg.yml | grep '"msg"' "msg": "missing: ['svn']"
Other loop helpers
| Need | Write |
|---|---|
| index of the item | loop_control: {index_var: idx} |
| nested loops (every user × every group) | loop: "{{ users | product(groups) | list }}", then item.0, item.1 |
| a sub-list per item (each user's keys) | loop: "{{ users | subelements('keys') }}" |
| a numeric range | loop: "{{ range(1, 4) | list }}" |
rename item (needed in nested includes) |
loop_control: {loop_var: user} |
| slow down / batch API calls | loop_control: {pause: 2} |
Loops vs module lists
Some modules take a list directly, which is much faster than a loop because the module runs once:
- name: Packages in one transaction (fast)
ansible.builtin.apt:
name: [nginx, curl, jq]
- name: Same with a loop (one apt call per package; avoid)
ansible.builtin.apt:
name: "{{ item }}"
loop: [nginx, curl, jq]Test yourself
How do you loop over a dictionary settings?
loop: "{{ settings }}"loop: "{{ settings | dict2items }}", thenitem.key/item.valuewith_items: settings.keys- Dictionaries can't be looped
What does a variable registered on a looped task contain?
- Only the last result
- A
resultslist with one result per item - The first result
- Nothing
Why set loop_control.label?
- To sort the loop
- To print a short label per item instead of the whole item (which may contain secrets)
- To rename
item - It is required