Loops and Conditional Tasks in Ansible

Ansible, one of the most popular open-source automation tools, helps IT professionals and DevOps teams automate various infrastructure tasks. When creating Ansible playbooks, you often need to execute tasks multiple times or conditionally. This is where loops and conditional tasks come into play.

In this article, we will delve into loops and conditional tasks in Ansible, exploring how they function, how to implement them in your playbooks, and how they can streamline automation processes. We’ll also highlight essential Ansible keywords to ensure a smooth and efficient automation process.

What Are Loops in Ansible?

Introduction to Loops

Loops in Ansible allow you to repeat tasks multiple times, making automation simpler and reducing redundancy in your playbooks. Rather than writing the same task multiple times for different items (e.g., multiple users, packages, or files), you can use loops to handle them all in one go. This enhances code readability and maintainability.

Common Loop Types in Ansible

Ansible supports several ways to implement loops. The most common ones include:

  1. Simple Loops: Iterate over a list of items.
  2. Loop with Dictionary: Iterate over key-value pairs in a dictionary.
  3. Loop with Indexes: Useful for scenarios where you need the index of the item in the loop.
  4. Loop with JSON Data: Loops can be used with structured data like JSON or YAML to process lists of objects.

How to Implement Loops in Ansible?

Here is a simple example of a loop that installs multiple packages:

 

---
- name: Install packages
  hosts: all
  tasks:
    - name: Install package
      ansible.builtin.yum:
        name: "{{ item }}"
        state: present
      loop:
        - httpd
        - vim
        - git

In this example, Ansible will iterate over the list of packages (httpd, vim, git) and install each one on the target host.

Advanced Looping Features

  1. Loop with with_items: Although loop is the newer standard, with_items is still widely used, particularly for backward compatibility.

    Example:

     
     
- name: Install packages
  yum:
    name: "{{ item }}"
    state: present
  with_items:
    - httpd
    - vim
    - git

Using loop_control: This can be used to modify the behavior of the loop, such as customizing the item index or setting a custom variable.

Example:

 

- name: Install packages with custom index
  yum:
    name: "{{ item }}"
    state: present
  loop:
    - httpd
    - vim
    - git
  loop_control:
    index_var: idx

What Are Conditional Tasks in Ansible?

Introduction to Conditional Tasks

Conditional tasks in Ansible allow you to execute tasks based on specific conditions. These conditions help you determine if a task should be run, depending on certain factors, such as the result of previous tasks, variables, or system states.

By using conditionals, you can ensure that your playbooks are flexible and behave dynamically based on the target host’s state, environment, or input.

Common Ansible Conditional Syntax

The most commonly used syntax for conditionals in Ansible is the when statement. The when statement controls whether a task will run based on an evaluated condition.

How to Implement Conditional Tasks in Ansible?

Here’s an example where a task runs only if a specific variable is defined:

 

- name: Install package if variable is set
  yum:
    name: "{{ package_name }}"
    state: present
  when: package_name is defined

n this example, the task will only run if the variable package_name is defined.

Conditional Task Examples

  • Running Tasks Based on Variables:

 

- name: Install Apache if web_server is true
  yum:
    name: httpd
    state: present
  when: web_server == true
  • Running Tasks Based on Host Facts:

 

- name: Install Nginx on Ubuntu
  yum:
    name: nginx
    state: present
  when: ansible_facts['os_family'] == 'Debian'

Combining Multiple Conditions: You can also combine multiple conditions using logical operators such as and, or, and not:

- name: Install Nginx if both conditions are true
  yum:
    name: nginx
    state: present
  when: ansible_facts['os_family'] == 'Debian' and nginx_installed == true

Nested Conditional Logic

Sometimes, you may need to execute tasks only if a set of conditions are met. In such cases, you can nest when conditions:

 

- name: Install Nginx if server is Ubuntu and nginx_installed is true
  yum:
    name: nginx
    state: present
  when:
    - ansible_facts['os_family'] == 'Debian'
    - nginx_installed == true

Combining Loops and Conditionals in Ansible

One of the key benefits of Ansible is the ability to combine loops and conditionals in the same task to create more complex logic. For example, you might want to loop over a list of packages and install them only if certain conditions are met.

Example: Installing Packages Conditionally with Loops

 

- name: Install specific packages if not already installed
  yum:
    name: "{{ item }}"
    state: present
  loop:
    - httpd
    - vim
    - git
  when: ansible_facts['os_family'] == 'RedHat'

In this example, the loop iterates over the list of packages, but the task will only execute if the host’s OS family is RedHat.

Example: Combining Loops with when to Execute Conditional Logic

 

- name: Install packages for web servers
  yum:
    name: "{{ item }}"
    state: present
  loop:
    - httpd
    - nginx
    - apache2
  when: ansible_facts['os_family'] == 'Debian' or ansible_facts['os_family'] == 'RedHat'

This playbook will install different packages based on the OS family, demonstrating how loops and conditionals can be efficiently combined.

Ashutosh Dixit

I am currently working as a Senior Technical Support Engineer with VMware Premier Services for Telco. Before this, I worked as a Technical Lead with Microsoft Enterprise Platform Support for Production and Premier Support. I am an expert in High-Availability, Deployments, and VMware Core technology along with Tanzu and Horizon.

Leave a Reply