Ansible Automation

Automate Repetition with Ansible Loops

Lesson 10 of 12 · 8 min · Intermediate

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.

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

dict_loop.yml
- 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_loop.yml
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.

index_loop.yml
- name: Loop with index
  debug:
    msg: "Item number {{ index }} is {{ item }}"
  loop:
    - apple
    - banana
  loop_control:
    index_var: index