Table of Contents

Ansible - Loop

About

loop in Ansible are done with look up plugin 1) 2) that returns variables for each selectionned item that you can use in your template.

Management

Nested

loop in Ansible are never nested but you can combine list

- name: give users access to multiple databases
  mysql_user:
    name: "{{ item[0] }}"
    priv: "{{ item[1] }}.*:ALL"
    append_privs: yes
    password: "foo"
  loop: "{{ ['alice', 'bob'] |product(['clientdb', 'employeedb', 'providerdb'])|list }}"

With Items

- name: Install mapr-core
  vars:
    packages_Suse: ['mapr-compat-suse', 'mapr-core', 'mapr-core-internal']
    packages_RedHat: ['mapr-core', 'mapr-core-internal']
    packages_Debian: ['mapr-core', 'mapr-core-internal']
  package: name={{ item }} state=present
  with_items: "{{ vars['packages_' + ansible_os_family] }}"
  register: core_result

Include Loop

- name: Issuer
  tags: cert-manager-issuer
  loop: "{{ cert_manager_issuers }}"
  loop_control:
    loop_var: cert_manager_issuer # the name of the variable in the include task file
  ansible.builtin.include_tasks:
    file: cert-manager-issuer-cloudflare-solver.yml
    apply:
      tags: cert-manager-issuer

For Files

See the file system page loop section where you can find the with_fileglob and with_filetree lookup.