Low Orbit Flux Logo 2 F

Ansible - Loops

with_ can be used for looping
loop added in 2.5, not full replacement for with_, equivalent to with_list, best for simple loops

Using loop:




- name: Example
  ansible.builtin.debug:
    var: item
  loop:
    - 1
    - [2,3]
    - 4

- name: Example
  ansible.builtin.debug:
    var: item
  loop: "{{ [1, [2,3] ,4] | flatten(1) }}"


Using with_:




- name: Example
  ansible.builtin.debug:
    var: item
  with_items:
    - 1
    - [2,3]
    - 4


Examples and Usage

Basic loop usage example:




- name: add several users
  user:
    name: "{{ item }}"
    state: present
    groups: "wheel"
  loop:
     - testuser1
     - testuser2


Loop over pre-defined list :




loop: "{{ somelist }}"


Don’t need a loop, can pass a list in this case:




- name: optimal yum
  yum:
    name: "{{  list_of_packages  }}"
    state: present


Loop over list of hashes:




- name: add several users
  user:
    name: "{{ item.name }}"
    state: present
    groups: "{{ item.groups }}"
  loop:
    - { name: 'testuser1', groups: 'wheel' }
    - { name: 'testuser2', groups: 'root' }


Lookups and With

No ( suboptimal to use lookup with loop ):




loop: "{{ lookup('fileglob', '*.txt', wantlist=True) }}"


Yes:




with_fileglob: '*.txt'