TExcelTAD

Loops

loop: runs a task once for each item of a list; the current item is {{ item }}. It replaces the older with_items, with_dict and friends, which still work but are not what new code should use.

Lists and lists of dictionaries

bash · try it yourself
cat > loops.yml <<'YML'
- name: Loops
  hosts: localhost
  gather_facts: false
  vars:
    app_dirs: [conf, data, logs]
    app_users:
      - {name: deploy, shell: /bin/bash}
      - {name: backup, shell: /usr/sbin/nologin}
  tasks:
    - name: Directories
      ansible.builtin.file:
        path: "app/{{ item }}"
        state: directory
        mode: "0755"
      loop: "{{ app_dirs }}"

    - name: One line per user (stand-in for the user module)
      ansible.builtin.lineinfile:
        path: app/conf/users
        line: "{{ item.name }}:{{ item.shell }}"
        create: true
        mode: "0644"
      loop: "{{ app_users }}"
      loop_control:
        label: "{{ item.name }}"
YML
ansible-playbook loops.yml | grep -E '^(ok|changed)'
cat app/conf/users
changed: [localhost] => (item=conf)
changed: [localhost] => (item=data)
changed: [localhost] => (item=logs)
changed: [localhost] => (item=deploy)
changed: [localhost] => (item=backup)
deploy:/bin/bash
backup:/usr/sbin/nologin

loop_control.label shortens what is printed per item: without it, Ansible prints the whole dictionary, which for a user with an SSH key and a password hash is long, and may print secrets.

Dictionaries: dict2items

loop needs a list. Turn a dictionary into a list of {key, value} items:

bash · try it yourself
cat > dict.yml <<'YML'
- name: Loop over a dictionary
  hosts: localhost
  gather_facts: false
  vars:
    sysctl_settings:
      net.ipv4.ip_forward: 0
      net.ipv4.conf.all.rp_filter: 1
      kernel.kptr_restrict: 2
  tasks:
    - name: Write a sysctl drop-in (a stand-in for ansible.posix.sysctl)
      ansible.builtin.lineinfile:
        path: 99-hardening.conf
        regexp: "^{{ item.key }} ="
        line: "{{ item.key }} = {{ item.value }}"
        create: true
        mode: "0644"
      loop: "{{ sysctl_settings | dict2items }}"
      loop_control:
        label: "{{ item.key }}"
YML
ansible-playbook dict.yml | grep -E '^(ok|changed)'
cat 99-hardening.conf
changed: [localhost] => (item=net.ipv4.ip_forward)
changed: [localhost] => (item=net.ipv4.conf.all.rp_filter)
changed: [localhost] => (item=kernel.kptr_restrict)
net.ipv4.ip_forward = 0
net.ipv4.conf.all.rp_filter = 1
kernel.kptr_restrict = 2

On a real server the task is ansible.posix.sysctl: {name: "{{ item.key }}", value: "{{ item.value }}", sysctl_file: /etc/sysctl.d/99-hardening.conf}, which also applies the value live; it needs root.

Registering a loop

A registered loop result holds a results list, one entry per item, each with its own item, changed, stdout…:

bash · try it yourself
cat > reg.yml <<'YML'
- name: Register in a loop
  hosts: localhost
  gather_facts: false
  tasks:
    - name: Check some commands
      ansible.builtin.command: "which {{ item }}"
      loop: [git, jq, svn]
      register: which
      changed_when: false
      failed_when: false

    - name: Missing tools
      ansible.builtin.debug:
        msg: "missing: {{ which.results | rejectattr('rc', 'eq', 0) | map(attribute='item') | list }}"
YML
ansible-playbook reg.yml | grep '"msg"'
    "msg": "missing: ['svn']"

Other loop helpers

Need Write
index of the item loop_control: {index_var: idx}
nested loops (every user × every group) loop: "{{ users | product(groups) | list }}", then item.0, item.1
a sub-list per item (each user's keys) loop: "{{ users | subelements('keys') }}"
a numeric range loop: "{{ range(1, 4) | list }}"
rename item (needed in nested includes) loop_control: {loop_var: user}
slow down / batch API calls loop_control: {pause: 2}

Loops vs module lists

Some modules take a list directly, which is much faster than a loop because the module runs once:

yaml
- name: Packages in one transaction (fast)
  ansible.builtin.apt:
    name: [nginx, curl, jq]

- name: Same with a loop (one apt call per package; avoid)
  ansible.builtin.apt:
    name: "{{ item }}"
  loop: [nginx, curl, jq]

Test yourself

How do you loop over a dictionary settings?

  1. loop: "{{ settings }}"
  2. loop: "{{ settings | dict2items }}", then item.key/item.value
  3. with_items: settings.keys
  4. Dictionaries can't be looped

What does a variable registered on a looped task contain?

  1. Only the last result
  2. A results list with one result per item
  3. The first result
  4. Nothing

Why set loop_control.label?

  1. To sort the loop
  2. To print a short label per item instead of the whole item (which may contain secrets)
  3. To rename item
  4. It is required