# ansible / iteration / loops
Automate Repetition with Ansible Loops
Loops in Ansible allow you to repeat a task multiple times using different values. Instead of writing separate tasks for each user, file, or package, you define the task once and provide a list.
The Basic Loop
The loop keyword is used to iterate over a list of items. Inside the task, the current item being processed in the iteration is accessed using the magic {{ item }} variable.
- name: Create multiple users user: name: "{{ item }}" state: present loop: - alice - bob - charlie
Dictionaries & Variables
Iterating Over Dictionaries
If you need to pass multiple associated values (like a username and their specific group), you can use a list of dictionaries. You then access the keys using dot notation: {{ item.name }}.
- name: Create users with specific groups user: name: "{{ item.name }}" groups: "{{ item.groups }}" state: present loop: - { name: 'alice', groups: 'wheel' } - { name: 'bob', groups: 'developers' }
Loops with Variables
Instead of hardcoding the list directly inside the task, you can define your list in the vars section to keep the playbook logic extremely clean.
vars: my_packages: - nginx - git - curl tasks: - name: Install packages apt: name: "{{ item }}" state: present loop: "{{ my_packages }}"
Loop Control & Pro Tips
Sometimes you need more than just the item itself. If you need to know the current index (position) of the item being processed, you can extend your loop using loop_control.
- name: Loop with index debug: msg: "Item number {{ index }} is {{ item }}" loop: - apple - banana loop_control: index_var: index
Before Ansible 2.5, loops exclusively used the with_items keyword. While with_items still works for backward compatibility, loop is now the modern, officially recommended way to perform simple iterations.
Loops help dramatically reduce code duplication by running the exact same module multiple times with different parameters. Using loop with the {{ item }} variable is the most efficient way to manage repetitive resources like users, files, and packages.