[Ansible] – How to create loops?

Simple loop

To create loops the attribute with_items is used to define that the action/task will be performed for all items of some collection/dictionary. Following an example.

vars:
  my_services:
    - firewalld
    - httpd

tasks:
  - name: Start services
    service:
      name: "{{ item }}"
      state: started
    with_items: "{{ my_services }}"

Check loops

It is possible to check if items are present in groups. Following an example.

- name: Users exist and are in the groups 
  user:
    name: "{{ item.name }}"
    state: present
    groups: "{{ item.groups }}"
  with_items:
    - { name: 'camila', groups: 'admin' }
    - { name: 'allan', groups: 'sales' }

Complex loops

Use the attribute with_nested to create a loop inside another loop. Following an example.

vars:
  employees:
    - allan
    - camila
    - john
  mysql_databases:
    - customerdb
    - companydb
    - employeedb
    - admindb
    - salesdb
tasks:
  - name: Check if employees has privileges on all databases
    mysql_user:
      name: "{{ item[0] }}"
      priv: "{{ item[1] }}.*:ALL"
      append_privs: yes
      password: root
    with_nested:
      - "{{ employees }}"
      - "{{ mysql_databases }}"

For further information check the Loops Ansible docs.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s