# ansible / iteration / loops

Iterate Tasks with Loops

Stop duplicating your task blocks. By leveraging Ansible's loop keyword, you can execute a single module multiple times dynamically, feeding it a list of distinct items.

$ ls -d /home/shannn/dev*
Output/home/shannn/dev1
/home/shannn/dev2
Result2 directories created
{{ item }}
magic variable
loop
keyword
1 task
playbook
# overview

The DRY Principle

"Don't Repeat Yourself." If you need to create five directories, write five user accounts, or install ten packages, writing separate tasks for each inflates your playbook and makes it harder to maintain. Loops solve this elegantly.

efficient

Reduced Lines of Code

A single file module handles the logic, while the loop block acts as the payload data. Adding a third directory is as simple as adding one line to the list.

dynamic

The {{ item }} Variable

Ansible automatically iterates through the list, temporarily assigning each value to the magic variable {{ item }} during task execution.

# playbook

The full task list

loop_dirs.ymlYAML
1 2 3 4 5 6 7 8 9 10 11 12 13
---
- name: createdirectories in loop
  hosts: localhost
  become: yes
  tasks:
    - name: create directory
      file:
        name: "/home/shannn/{{ item }}"
        state: directory
      loop:
        - dev1
        - dev2

Run order

  • iteration 1

    Ansible reads the first item in the list, maps {{ item }} to dev1, and executes the file module.

    item == "dev1"
  • iteration 2

    Ansible reads the second item, maps {{ item }} to dev2, and executes the file module again.

    item == "dev2"
# verify

Check the loop results

When the loop runs, Ansible will show a separate output status for each item in the terminal. You can then verify the directory structure on the host.

terminal
$ ansible-playbook loop_dirs.yml
TASK [create directory] ********************************************
changed: [localhost] => (item=dev1)
changed: [localhost] => (item=dev2)
 
$ ls -l /home/shannn/ | grep dev
drwxr-xr-x 2 root root 4096 Jul 8 19:18 dev1
drwxr-xr-x 2 root root 4096 Jul 8 19:18 dev2
 
$
# notes

Lessons from running this in production

INFO

In older versions of Ansible, you would use with_items: instead of loop:. They function similarly, but loop is the modern, recommended standard.

WARN

Notice the use of name: in the file module? While it works perfectly, path: is the standard, documented parameter for directories. They are aliases of each other.

OK

You correctly enclosed "/home/shannn/{{ item }}" in quotes. Because it contains a Jinja2 template variable, those quotes are required to prevent YAML parsing errors.