LOGBOOK

HELP

← again tap: answer good → ↑ swipe up at the end: next

1 / 9 Part 1 of 6
Other keys: show • Space: good • 1-4: rate • 0: skip • 5: flag

Question

What problem does a loop solve in an Ansible playbook?

Answer

It replaces several near-identical tasks that call the same module with one task that repeats over a list of values.

Two copy-pasted service tasks collapse into one task with a loop over postfix and dovecot

* Two tasks that differ only in one value become one task with a loop. *

Without a loop, making sure five users exist means writing five tasks that are identical except for the user name. That is tedious, and it is fragile: when you change an option (say, the shell every user gets), you have to change it in five places, and missing one leaves the hosts inconsistent.

With a loop you write the task once and give it the list of values. Ansible runs the task once per element and puts the current element in the loop variable item:

- name: Postfix and Dovecot are running
  ansible.builtin.service:
    name: "{{ item }}"
    state: started
  loop:
    - postfix
    - dovecot

The two hand-written tasks (one for postfix, one for dovecot) become this single task. The value that changes moves into the list; everything that stays the same is written once.

Go deeper:

or press any other key

Question

In a simple Ansible loop, which keyword supplies the list, which variable holds the current value, and how can the list come from a variable?

Answer

loop: supplies the list, item holds the current element on each pass, and loop: "{{ my_list }}" takes the list from a variable.

The loop keyword sits at task level (next to name and the module) and takes a list. On each iteration Ansible sets item to the next element and runs the module again, so any module argument written as "{{ item }}" gets a different value per pass.

The list does not have to be written inline. Keeping it in a variable separates the data (which services) from the logic (make them run), so the list can be changed per environment without touching the task:

vars:
  mail_services:
    - postfix
    - dovecot

tasks:
  - name: Postfix and Dovecot are running
    ansible.builtin.service:
      name: "{{ item }}"
      state: started
    loop: "{{ mail_services }}"

The quotes around "{{ mail_services }}" are required: a YAML value that starts with { would otherwise be read as the start of a dictionary, not as a Jinja2 expression.

Go deeper:

or press any other key