Perform Looping In Ansible

Posted By : Abhishek Gupta | 30-Jun-2020

Ansible

Loading...

What is Ansible?

Ansible is an open-source tool for configuration management and application deployment tool. It can run both in Unix and Windows operating systems.

In this blog, you will get to know how you can perform looping in ansible.

Introduction about Loops:

In programming we use a loop to run the same code multiple times. In ansible, we use loop to run multiple methods to repeat tasks until a condition matches.

Scenario 1:

We need to create a playbook that will install several packages.

loops.yml

  • Hosts: all

name: ansible simple loop example

apt:

name: “{{ item}}”

State: present

with_items:

  • python3
  • git
  • vim

Here instead of writing 3 different tasks we have combined all the 3 tasks into a single task and run via loop so this is one of the advantages of using a loop.

In every iteration, the value in with_items block will be inserted in the place of the item. So first it will install python3 then git and last vim in the worker system

Scenario 2:

Ansible loop with index

In some cases, you must be aware of index value. Ansible provides with_indexed_items for the same. Index value always starts with 0. According to your use cases, you can also perform some basic operations like add, subtract in the index value.

loopindex.yml

- hosts: all

tasks:

- name: Ansible loop with index example

debug:

msg: "echo loop index at {{ item.0 }} and value at {{item.1}}"

with_indexed_items:

- "hello1"

- "hello2"

- "hello3"

Output:

The above picture shows the output when we run playbook.

Scenario 3:

Ansible Loop with conditional

You can also use the when conditional statement along with the loop according to your use cases.

loopwithwhen.yml

- hosts: all

tasks:

- name: Ansible loop with conditional example

debug:

msg: "{{ item }}"

with_items:

- "hello1"

- "hello2"

- "hello3"

when: ansible_distribution == "CentOS"

This playbook will run only when ansible_distribution is CentOS.

Ansible is an automation tool that performs configuration management, application deployment, intraservice orchestration, and provisioning. We are a Python Development Company with a goal of transforming enterprises with automation tools through our custom development services. We use a massive tech stack comprising Java, Python, Angular, and more to achieve this. Get in touch with our experts to employ these technologies now!