# 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.

Task: Create multiple users
Item 1changed: [alice]
Item 2changed: [bob]
Item 3changed: [charlie]
loop
Keyword
{{ item }}
Variable
# fundamentals

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.

basic_loop.ymlYAML
1 2 3 4 5 6 7 8
- name: Create multiple users
  user:
    name: "{{ item }}"
    state: present
  loop:
    - alice
    - bob
    - charlie
# advanced-data

Dictionaries & Variables

complex data

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 }}.

dict_loop.ymlYAML
1 2 3 4 5 6 7 8
- name: Create users with specific groups
  user:
    name: "{{ item.name }}"
    groups: "{{ item.groups }}"
    state: present
  loop:
    - { name: 'alice', groups: 'wheel' }
    - { name: 'bob', groups: 'developers' }
clean code

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_loop.ymlYAML
1 2 3 4 5 6 7 8 9
vars:
  my_packages:
    - nginx
    - git
    - curl
tasks:
  - name: Install packages
    apt:
      name: "{{ item }}"
      state: present
    loop: "{{ my_packages }}"
# control

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.

index_loop.ymlYAML
1 2 3 4 5 6 7 8
- name: Loop with index
  debug:
    msg: "Item number {{ index }} is {{ item }}"
  loop:
    - apple
    - banana
  loop_control:
    index_var: index
💡 PRO TIP

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.

FINAL SUMMARY

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.