Task

Iterate Tasks with Loops

Ansible · 10 min · Practical

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.

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.

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.

The {{ item }} Variable

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

The full task list

loop_dirs.yml
---
- 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"

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

$

Lessons from running this in production