# 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.
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
--- - 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 == "dev1"{{ item }}todev1, and executes the file module. - iteration 2
Ansible reads the second item, maps
item == "dev2"{{ item }}todev2, and executes the file module again.
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.
Lessons from running this in production
In older versions of Ansible, you would use with_items: instead of loop:. They function similarly, but loop is the modern, recommended standard.
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.
You correctly enclosed "/home/shannn/{{ item }}" in quotes. Because it contains a Jinja2 template variable, those quotes are required to prevent YAML parsing errors.