Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

Ansible loops: iterate over lists, dicts and lookup results

14 min read
Improve this page

Logo Ansible

loop: is the modern Ansible directive (2.5+) for iterating a task over a list, a dict or the result of a lookup. It replaces the older with_items:, with_dict: and with_subelements:; the next page covers them: Legacy with_* loops (in French). This page covers the loop: syntax, the loop_control: option (label, index_var, pause), combining it with when:, and the usual patterns: iterating over a list of dicts, over a dict, over the result of lookup('fileglob', ...), or walking through two levels of nested lists.

It is the directive most used to parameterize a playbook: a single module that creates 10 users by looping over a list, instead of 10 duplicated tasks.

What you will learn

  • The loop: <list> syntax and the item variable
  • loop_control:: label, index_var, pause, extended
  • Iterating over a list of dicts: loop: + item.<key>
  • Iterating over a dict with dict2items
  • Walking through two levels of lists with subelements, or with include_tasks and loop_var
  • Combining loop: + when:: filtering per item
  • register: on a loop: getting the list of results

Prerequisites

The loop: syntax

- name: Install several packages
ansible.builtin.dnf:
name: "{{ item }}"
state: present
loop:
- nginx
- redis
- postgresql

At each iteration, item holds one element of the list. The task runs 3 times.

Iterating over a list of dicts

This is the most common pattern in Ansible. Each item is a dict, and you reach its keys with item.<key>:

vars:
users:
- { name: alice, shell: /bin/bash, enabled: true }
- { name: bob, shell: /bin/zsh, enabled: false }
- { name: charlie, shell: /bin/bash, enabled: true }
tasks:
- name: Create the users
ansible.builtin.user:
name: "{{ item.name }}"
shell: "{{ item.shell }}"
state: present
loop: "{{ users }}"
loop_control:
label: "{{ item.name }}"
when: item.enabled

Console output:

TASK [Create the users]
skipping: [db1.lab] => (item=bob)
changed: [db1.lab] => (item=alice)
changed: [db1.lab] => (item=charlie)

Without loop_control.label:, Ansible would print the whole dict at each iteration, which is unreadable.

loop_control:, loop options

OptionEffect
label: "<expr>"Console display (instead of the whole dict)
index_var: idxVariable holding the current index (0-based)
pause: <seconds>Pause between each iteration (useful for rate-limited APIs)
extended: trueEnables ansible_loop.first, ansible_loop.last, ansible_loop.index
- name: Full loop_control demo
ansible.builtin.debug:
msg: "Item {{ idx }} of {{ users | length }}: {{ item.name }} (last={{ ansible_loop.last }})"
loop: "{{ users }}"
loop_control:
label: "{{ item.name }}"
index_var: idx
pause: 1
extended: true

Iterating over a dict with dict2items

vars:
ports:
nginx: 80
redis: 6379
postgresql: 5432
tasks:
- name: List the ports
ansible.builtin.debug:
msg: "{{ item.key }}: {{ item.value }}"
loop: "{{ ports | dict2items }}"
loop_control:
label: "{{ item.key }}"

dict2items turns {a: 1, b: 2} into [{key: a, value: 1}, {key: b, value: 2}]. Conversely, items2dict rebuilds a dict.

Iterating over a lookup

- name: Distribute all local certificates
ansible.builtin.copy:
src: "{{ item }}"
dest: "/etc/ssl/{{ item | basename }}"
mode: "0644"
loop: "{{ query('fileglob', 'files/certs/*.pem') }}"

query('fileglob', ...) returns a list of paths matching the glob on the control node. Prefer query over lookup when iterating (query always returns a list).

loop: and when: together

when: is evaluated at each iteration:

- name: Install only the enabled services
ansible.builtin.dnf:
name: "{{ item.name }}"
state: present
loop: "{{ services }}"
when: item.enabled

For the iterations where when: is false, the task is marked skipped (not failed).

register: on a loop

When you capture the output of a task inside a loop, the result is a list:

- name: Check URLs in a loop
ansible.builtin.uri:
url: "https://{{ item }}/health"
status_code: 200
loop:
- api.example.com
- app.example.com
register: health_results
- name: Show all statuses
ansible.builtin.debug:
msg: "{{ item.item }} → {{ item.status }}"
loop: "{{ health_results.results }}"

The result lives in health_results.results (a list), and each entry contains the original item plus the task fields (status, content, etc.).

The .results suffix is systematic, whatever name you give to the register:: a register: result is read as result.results, a register: resultat is read as resultat.results. This explains a message that often puzzles people on a looped task. Looking up resultat.stdout fails with 'dict object' has no attribute 'stdout', not because the capture failed, but because stdout does not exist at the root: it lives in each entry of resultat.results, one per iteration.

Practical case: creating users with filtering

Here is the example validated on the ecrire-code-boucles-loop lab:

---
- name: Challenge boucles-loop
hosts: db1.lab
become: true
vars:
challenge_users:
- { name: chal_alice, shell: /bin/bash, enabled: true }
- { name: chal_bob, shell: /bin/zsh, enabled: false }
- { name: chal_charlie, shell: /bin/bash, enabled: true }
tasks:
- name: Create the active users
ansible.builtin.user:
name: "{{ item.name }}"
shell: "{{ item.shell }}"
state: present
loop: "{{ challenge_users }}"
loop_control:
label: "{{ item.name }}"
when: item.enabled
- name: Write the summary
ansible.builtin.copy:
dest: /tmp/loop-result.txt
content: "{{ challenge_users | selectattr('enabled') | map(attribute='name') | sort | join(',') }}\n"
mode: "0644"

alice and charlie are created, bob is skipped. The loop-result.txt summary is generated on the Jinja side without a loop (through selectattr | map | sort | join).

How do you nest two loops?

A task carries only one loop:, and loop is not a keyword of block: (the grouping of several tasks under one block): putting loop: on a block fails with 'loop' is not a valid attribute for a Block. To walk through "each user, and for each one every file", you therefore have to reduce the double loop to a single one, or hand the inner loop to an included task file.

The idiomatic form is the subelements filter. It turns the list of users into a single list of [user, file] pairs: inside the loop, item.0 is the user and item.1 the file. It is the modern form of the old with_subelements, covered in Legacy with_* loops (in French).

vars:
users:
- { name: alice, files: [.bashrc, .vimrc] }
- { name: bob, files: [.bashrc] }
tasks:
- name: Show each user/file pair
ansible.builtin.debug:
msg: "User {{ item.0.name }}, file {{ item.1 }}"
loop: "{{ users | subelements('files') }}"
loop_control:
label: "{{ item.0.name }}/{{ item.1 }}"

When the inner loop has to carry several tasks, the second form is to loop over include_tasks. The outer task includes a task file for each user, and that file contains its own loop. Both levels would use item: loop_var gives each level's variable a distinct name, and prevents the inner loop from shadowing the outer one. Without it, Ansible warns The loop variable 'item' is already in use. The fichiers-user.yml file sits next to the playbook; the difference between include_* and import_* is detailed in Import vs Include (in French).

# playbook
tasks:
- name: Outer loop over the users
ansible.builtin.include_tasks: fichiers-user.yml
loop: "{{ users }}"
loop_control:
loop_var: user_item
label: "{{ user_item.name }}"
fichiers-user.yml
- name: Inner loop over the current user's files
ansible.builtin.debug:
msg: "User {{ user_item.name }}, file {{ file_item }}"
loop: "{{ user_item.files }}"
loop_control:
loop_var: file_item

At run time, both forms print the same three pairs: alice with .bashrc and .vimrc, bob with .bashrc. Prefer subelements as long as the inner loop has a single task, and include_tasks when it has several.

Frequent pitfalls

SymptomCauseFix
The loop prints the whole dict at each iterationNo loop_control: label:Always add label: "&#123;&#123; item.name &#125;&#125;"
'dict object' has no attribute 'foo'The key does not exist in some itemsitem.foo | default('value') or when: 'foo' in item
Loop too slowThe module supports a list but you loop anywayPass the list directly to the module (name: ['a', 'b'])
register with a loop returns a dict, not a listThe list sits under register_var.resultsUse register_var.results, not register_var directly
'loop' is not a valid attribute for a Blockloop: placed on a block:loop: goes on a task: subelements for a double loop, or include_tasks in a loop
loop: does not propagate handlersBy design (a handler is deduplicated)No fix
loop: with a pause: slows the play downpause: is deliberate (API rate limit)Reduce the value or remove the pause:

Key takeaways

  • loop: <list> + item = the modern loop (Ansible 2.5+). with_* is legacy.
  • loop_control: label: "{{ item.name }}" makes the console output readable.
  • To iterate over a dict, use {{ ports | dict2items }} (key/value).
  • register: on a loop stores the list in var.results.
  • If the module supports a list (dnf, apt), pass the list directly instead of looping: it is faster.
  • For a double loop, use subelements, or include_tasks with loop_var on each level. loop: does not exist on a block:.
  • when: is evaluated at each iteration: useful for filtering per item.

Put it into practice

A loop is judged by its console output as much as by its result. The lab has you iterate over a simple list and then over a list of dicts, make the display readable with loop_control: label, and walk through a dictionary with dict2items. The validation counts the accounts actually created on the machine, which highlights the filtering done by when: at each iteration.