Ansible loop

How to work with Ansible loop

Ansible loop provides a lot of methods to repeat certain tasks until a condition is met.

A basic example which can be used to install a lot of Linux packages can be written like the below example.


In the above task, instead of writing 3 separate task we have consolidated them into a single task.

In each iteration, the value of with_items block will be inserted in place of {{ item }}. 

Ansible loop with Index

In some scenarios knowing the index value might come in handy. You can use the “with indexed_items” for this. The loop index will be available at item.0 and the value will be available at item.1. index value starts at zero as usual.

You can also make changes to the index value like addition, subtraction etc.

Ansible loop with conditional

You can also use the “when” conditional statement along with the loop structure. Thus you can control the looping based on a variable or system facts.

The following example will run the task when the loop value is the same as the “loop_1” variable. Note that “item” is not enclosed in double brackets.

Looping through Dictionaries

You can loop through Ansible dictionary variable using the with_dict parameter. In the following task, I have declared a variable ‘Fruits’ with 3 key-value pairs. I am using the with_dict to loop through all the values.

Also published on Medium.

Leave a Reply

Notify of