A loop runs the same task once for every item in a list. Roboshop has 10 components. Instead of writing 10 tasks, you write one task and give it the list of components.
- Put the list under
loop:.
- On each pass, the current item is in the variable
item.
loop only accepts a list. Other data, like a dictionary or a range of numbers, has to be turned into a list first with a filter.
These are the ways to loop covered on this page:
- Simple list
- List of dictionaries
- Dictionary
- Range of numbers
- Nested loop
- loop_control
- loop with when
- loop with register
- until (retry loop)
- Old style: with_items
All the examples come from one roboshop playbook. These are the variables it uses:
- name: Ansible loops examples - roboshop
hosts: local
connection: local # run on this machine without SSH
gather_facts: false # no facts needed for these examples
vars:
components: [mongodb, rabbitmq, mysql, redis, catalogue, cart, user, shipping, payment, frontend]
servers:
- { name: mongodb, port: 27017, database: true }
- { name: redis, port: 6379, database: true }
- { name: catalogue, port: 8080, database: false }
- { name: frontend, port: 80, database: false }
db_ports:
mongodb: 27017
rabbitmq: 5672
mysql: 3306
redis: 6379
app_users:
- { server: catalogue, user: roboshop, home: /app, shell: /sbin/nologin }
- { server: cart, user: roboshop, home: /app, shell: /sbin/nologin }
- { server: user, user: roboshop, home: /app, shell: /sbin/nologin }
- { server: shipping, user: roboshop, home: /app, shell: /sbin/nologin }
- { server: payment, user: roboshop, home: /app, shell: /sbin/nologin }
envs: [dev, qa]
app_components: [catalogue, cart, user, shipping, payment]
1. Simple list
The most common loop. The task runs once for each value in the list, and item holds the current value. Here it runs once for each of the 10 roboshop components.
- name: Simple loop - one task per roboshop component
ansible.builtin.debug:
msg: "Setting up {{ item }}"
loop: "{{ components }}"
The output shows one line per component:
TASK [Simple loop - one task per roboshop component] ****************
ok: [localhost] => (item=mongodb) => { "msg": "Setting up mongodb" }
ok: [localhost] => (item=rabbitmq) => { "msg": "Setting up rabbitmq" }
ok: [localhost] => (item=mysql) => { "msg": "Setting up mysql" }
...
ok: [localhost] => (item=frontend) => { "msg": "Setting up frontend" }
The list doesn't have to be a variable. You can write it directly under loop:
- name: Inline list
ansible.builtin.debug:
msg: "Creating instance {{ item }}"
loop:
- mongodb
- catalogue
- frontend
2. List of dictionaries
When each item has several fields, like a server with a name and a port, each item is a dictionary. Read a field with item.<key>.
- name: List of dictionaries - one task per server
ansible.builtin.debug:
msg: "{{ item.name }} listens on port {{ item.port }}"
loop: "{{ servers }}"
Real example: the roboshop system user
In roboshop, every app component (catalogue, cart, user, shipping, payment) runs as a system user called roboshop. A system user is meant for running an application, not for people: it has no login shell (/sbin/nologin), and its home is /app, where the app code lives.
Each item in app_users describes the user for one app server:
- name: roboshop system user - one entry per app server
ansible.builtin.debug:
msg: "{{ item.server }}: create user {{ item.user }}, home {{ item.home }}, shell {{ item.shell }}"
loop: "{{ app_users }}"
loop_control:
label: "{{ item.server }}"
catalogue: create user roboshop, home /app, shell /sbin/nologin
cart: create user roboshop, home /app, shell /sbin/nologin
user: create user roboshop, home /app, shell /sbin/nologin
shipping: create user roboshop, home /app, shell /sbin/nologin
payment: create user roboshop, home /app, shell /sbin/nologin
On a real server, the task that creates the user looks like this. You run it on each app server, and Ansible already repeats a play for every host in the group, so you don't need a loop for the servers:
- name: Create the roboshop system user
hosts: catalogue
become: true
tasks:
- name: Create roboshop system user
ansible.builtin.user:
name: roboshop
comment: "roboshop system user"
system: true
home: /app
shell: /sbin/nologin
create_home: false
- name: Create /app directory owned by roboshop
ansible.builtin.file:
path: /app
state: directory
owner: roboshop
group: roboshop
3. Dictionary
loop can't read a dictionary directly. The dict2items filter turns it into a list where each item has a key and a value. Here the key is the database and the value is its port.
- name: Dictionary - database name and port
ansible.builtin.debug:
msg: "{{ item.key }} runs on port {{ item.value }}"
loop: "{{ db_ports | dict2items }}"
mongodb runs on port 27017
rabbitmq runs on port 5672
mysql runs on port 3306
redis runs on port 6379
4. Range of numbers
To loop over numbers, use range(start, end). It stops before the end number, so range(1, 4) gives 1, 2 and 3. Here it names three catalogue instances.
- name: Range - create 3 catalogue instances
ansible.builtin.debug:
msg: "catalogue-{{ item }}"
loop: "{{ range(1, 4) | list }}"
catalogue-1
catalogue-2
catalogue-3
5. Nested loop
Sometimes you need every combination of two lists, for example every app component in every environment. The product filter builds those pairs. In each pair, item.0 is from the first list (the environment) and item.1 is from the second (the component).
- name: Nested loop - every environment with every component
ansible.builtin.debug:
msg: "Deploying {{ item.1 }} to {{ item.0 }}"
loop: "{{ envs | product(app_components) | list }}"
Deploying catalogue to dev
Deploying cart to dev
...
Deploying payment to dev
Deploying catalogue to qa
...
Deploying payment to qa
6. loop_control
loop_control changes how the loop behaves. The three options you'll use most:
index_var: gives you the position of the current item, starting at 0.
label: what to print for each item in the output. Without it, Ansible prints the whole item, which gets long for dictionaries.
loop_var: renames item. You need this when one loop runs inside another, so the two item variables don't clash.
- name: loop_control - index and a short label
ansible.builtin.debug:
msg: "Server {{ idx + 1 }} of {{ servers | length }} is {{ item.name }}"
loop: "{{ servers }}"
loop_control:
index_var: idx
label: "{{ item.name }}"
- name: loop_control - rename item
ansible.builtin.debug:
msg: "Component: {{ component }}"
loop: "{{ app_components }}"
loop_control:
loop_var: component
Server 1 of 4 is mongodb
Server 2 of 4 is redis
Server 3 of 4 is catalogue
Server 4 of 4 is frontend
7. loop with when
When a task has both loop and when, the condition is checked for each item. Items where it is false are skipped, and the rest still run. Here only the database servers are printed.
- name: loop with when - only database servers
ansible.builtin.debug:
msg: "{{ item.name }} is a database server"
loop: "{{ servers }}"
when: item.database
loop_control:
label: "{{ item.name }}"
ok: [localhost] => (item=mongodb) => { "msg": "mongodb is a database server" }
ok: [localhost] => (item=redis) => { "msg": "redis is a database server" }
skipping: [localhost] => (item=catalogue)
skipping: [localhost] => (item=frontend)
8. loop with register
When you register a task that loops, the result of every pass is saved in a list called results. Each entry also remembers which item it was for, in item.
- name: loop with register - run a command for each app component
ansible.builtin.command: "echo starting {{ item }}"
loop: "{{ app_components }}"
register: start_out
changed_when: false
- name: Read the saved results
ansible.builtin.debug:
msg: "{{ item.item }} -> {{ item.stdout }}"
loop: "{{ start_out.results }}"
loop_control:
label: "{{ item.item }}"
catalogue -> starting catalogue
cart -> starting cart
user -> starting user
shipping -> starting shipping
payment -> starting payment
9. until (retry loop)
until is a different kind of loop: it runs one task again and again until a condition becomes true. It is mostly used to wait. For example, catalogue needs mongodb, so you wait until mongodb is ready before starting catalogue.
until: the condition to wait for.
retries: the maximum number of tries. If the condition is still false after that, the task fails.
delay: seconds to wait between tries.
In this example a counter goes up by 1 on each try, so the condition becomes true on the third try:
- name: until - wait for mongodb to be ready
ansible.builtin.shell: "n=$(cat /tmp/mongodb_check 2>/dev/null || echo 0); n=$((n+1)); echo $n > /tmp/mongodb_check; echo $n"
register: mongodb_check
until: mongodb_check.stdout | int >= 3
retries: 5 # try at most 5 times
delay: 1 # wait 1 second between tries
changed_when: false
- name: Clean up the counter file
ansible.builtin.file:
path: /tmp/mongodb_check
state: absent
FAILED - RETRYING: [localhost]: until - wait for mongodb to be ready (4 retries left).
FAILED - RETRYING: [localhost]: until - wait for mongodb to be ready (3 retries left).
ok: [localhost]
The "FAILED - RETRYING" lines are normal. They only mean mongodb wasn't ready yet.
10. Old style: with_items
Older playbooks use with_* keywords instead of loop. They still work, so you will see them in existing code, but loop is recommended for new playbooks.
- name: Old style - with_items
ansible.builtin.debug:
msg: "Setting up {{ item }}"
with_items: "{{ app_components }}"
How the old keywords map to loop:
with_items → loop
with_dict → loop with | dict2items
with_sequence → loop with range(...) | list
with_nested → loop with | product(...) | list
A tip for packages
Modules like dnf, apt and package accept a whole list in one go. Passing the list is faster than looping, because Ansible installs everything in one step instead of one package at a time. For example, on the frontend server:
- name: Install frontend packages in one step
ansible.builtin.dnf:
name: [nginx, git, curl]
state: present
Running the playbook
ansible-playbook -i inventory.ini ansible_loops.yaml
← Back to portfolio