How To Use Loops in Ansible Playbooks

When automating server setup, sometimes you’ll need to repeat the execution of the same task using different values. For instance, you may need to change permissions of multiple files, or create multiple users. To avoid repeating the task several times in your playbook file, it’s better to use loops instead.

In programming, a loop allows you to repeat instructions, typically until a certain condition is met. Ansible offers different looping methods, with the loop keyword being the most recommended option for longer term compatibility.

The following example creates three different files on the /tmp location. It uses the file module within a task that implements a loop using three different values.

Create a new file called playbook-06.yml in your ansible-practice directory:

  • nano ~/ansible-practice/playbook-06.yml

Then add the following lines to the new playbook file:


--- - hosts: all   tasks:     - name: creates users files       file:         path: /tmp/ansible-{{ item }}         state: touch       loop:         - sammy         - erika         - brian 

Save and close the file when you’re done.

Then, run ansible-playbook with the same connection arguments from the previous examples. Again, we’re using an inventory file named inventory and a user named sammy, but you should change these values accordingly:

  • ansible-playbook -i inventory playbook-06.yml -u sammy

You’ll get output like this, showing each individual item value that was used within the loop:

Output... TASK [creates users files] ****************************************************************************** changed: [] => (item=sammy) changed: [] => (item=erika) changed: [] => (item=brian) ... 

For more detailed information on how to use loops when writing Ansible playbooks, please refer to the official documentation.