How to use Loops in Ansible?

If you are writing code in any programming language there is always some code that is repetitive in nature. Just like any other programming language, Ansible has, its own way to use Loops. Here we will see how to use Loops in Ansible.

Using Simple Loops

Imagine you have a code where you create a text file for each fruit and without loops, you would have to use as below. So the scripts look untidy, and it’s a bit of a hassle to manage them.

-
    name: 'Create text files with the names of fruits'
    hosts: localhost
    gather_facts: False
    tasks:
        -
            command: touch Apple.txt
        -
            command: touch grapes.txt

Ansible has a cool way to use Loops, it provides two directives that are Loop and with_*. Your code would look as below if you would Loops.

- 
    name: 'Create text files with the names of fruits' 
    hosts: localhost
    gather_facts: False
    vars: 
        fruits: 
            - Apple 
            - Banana 
            - Grapes 
            - Orange 
    tasks: 
        - 
            command: 'touch "{{item}}"' 
            with_items: '{{ fruits }}' 

So what we have done in the above code is create a variable and Iterated over it and created a file with the fruit name. Another great example would be adding multiple users to a system.

- hosts: Remote Servers
  tasks:
    - name: Create new users
      user:
        name: '{{ item }}'
        state: present
      loop:
        - mohammed
        - mike
        - Rahul

In the above example, you can use the with_items directive as well instead of loop and it will give you the same results. So far we have seen how to iterate over a simple list, but in real-world you would be using complex loops most of the time. There is one more example of a simple loop that is restarting multiple services on a server.

If you haven’t read my previous post already on Ansible Playbook to start services please have a look where I have used the simple list to achieve the desired results.

As mentioned in Ansible Docs, there are more ways to Iterate over loops. Let’s have a look at how to iterate over Dictionary. A dictionary is a key:value pair of an unordered list. The simplest example of a Dictionary would be as below

Fruit: Banana
Vegetable: Cauliflower
Liquid: Water
Meat: Chicken

To Iterate over a dictionary you will have to use dict2items. Let’s iterate over the Dictionary above.

---
 - name: Working with loop module
   hosts: localhost
   gather_facts: false
   tasks:
     - name: Iterate over dictionary
       debug:
         msg:
          - "Buy a {{ item.key }} that is {{ item.value }}"

       loop: "{{ shopping_list | dict2items }}"
       vars:
         shopping_list:
            Fruit: Banana
            Vegetable: Cauliflower
            Liquid: Water
            Meat: Chicken

So in the above example we are iterating over Key using item.key and using item.value to iterate over Value.

Hope this guide will help you understand better.

Leave a Comment