ANSIBLE LOOPS

Introduction

Loops in Ansible allow you to repeat a task multiple times using different values. Instead of writing separate tasks for each item, you define the task once and provide a list of items.

1. Basic Loop Example

The loop keyword is used to iterate over a list. The current item in the iteration is accessed using the {{ item }} variable.

- name: Create multiple users
  user:
    name: "{{ item }}"
    state: present
  loop:
    - alice
    - bob
    - charlie

2. Iterating Over a List of Dictionaries

If you need to pass multiple values (like a username and a group), you can use a list of dictionaries.

- name: Create users with specific groups
  user:
    name: "{{ item.name }}"
    groups: "{{ item.groups }}"
    state: present
  loop:
    - { name: 'alice', groups: 'wheel' }
    - { name: 'bob', groups: 'developers' }

3. Using Loops with Variables

You can define your list in the vars section to keep the playbook clean.

vars:
  my_packages:
    - nginx
    - git
    - curl

tasks:
  - name: Install packages
    apt:
      name: "{{ item }}"
      state: present
    loop: "{{ my_packages }}"

4. Loop with Index

If you need to know the current index (position) of the item, you can use loop_control.

- 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 used with_items. While with_items still works, loop is now the recommended way to perform simple iterations.

Final Summary

"Loops help reduce code duplication by running the 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."