How to use Loops in Ansible playbook

Reading Time: 2 minutes

Loops:

Sometimes you want to repeat a task multiple times, In computer programming this is called as loops.Suppose you want to perform some repetitive task then one way would be duplicate tasks for multiple time something which can be quite tedious. Ansible loops are very effective to perform repetitive tasks with fewer lines of code.

Ansible provides the loopwith_<lookup>, and until keywords to execute a task multiple times.

What is lookup?

Lookups are an integral part of loops. Wherever you see with_, the part after the underscore is the name of a lookup. For this reason, most lookups output lists and take lists as input; for example, with_items uses the items lookup.

Lets see an example with playbook name loops.yml:

The loop keyword executes the same task multiple times. It  stores the value of each item in a variable called item.So, instead of specifying the names of the users to be added, simply specify a variable called item enclosed between double curly braces as shown below.

name: "{{ item }}"

Each of the items within the loop will be referenced by the variable name item.

--- 
- hosts: all
  become: yes
  tasks:
    -name: add user in nodes
     user: 
       name: "{{ item }}"
       state: present
     with_items:
       - user1
       - user2
       - user3

run the playbook using the following command

$ ansible-playbook loops.yml

To verify ,whether users created or not go inside node and run command $ cat /etc/passwd

If you have a list of hashes, you can reference subkeys in a loop. For example:

---
- hosts: all
  become: yes
  tasks:
      - name: add user in nodes
        user: 
          name: "{{ item.name }}" 
          uid: "{{ item.uid }}"
          state: present 
        loop:
          - { name: user1, uid: 2001 }
          - { name: user2, uid: 2002 }
          - { name: user3, uid: 2003 }

We can also reference a variable in loop which is outside our playbook .So let have a look how we can reference a variable that is defined in another file.

So lets create a file user_list.yml

---
users:
  - name: user1
    uid: 2001
  - name: user2
    uid: 2002
  - name: user3
    uid: 2003

So for referencing a variable defined in a file first we have to reference that file in our playbook.

Lets have a look on updated Playbook.

---
- hosts: all
  become: yes
  vars_files:
    - user_list.yml
  tasks:
      - name: add user in nodes
        user: 
          name: "{{ item.name }}" 
          uid: "{{ item.uid }}"
          state: present 
        loop: "{{ users }}"

For more you can reference Ansible official Document:https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html

Leave a Reply