How to Use When Conditional Statement in Ansible Playbook

In this guide, we will show you how to use when conditional statement in Ansible playbook with examples.

Ansible, the open-source automation tool, empowers system administrators and DevOps professionals to streamline complex IT processes. One of Ansible’s key features is its ability to execute tasks conditionally using the “when” statement.

Using When Conditional Statement in Ansible Playbook

Traditional programming language usually uses the if-else statement when more than one outcome is expected. In Ansible, ‘when’ statement is used instead to determine the outcome of a variable. So instead of using the if-else statement, you define what you want to happen. The syntax is as shown below:

 tasks:
   - name: Perform a task conditionally
     command: some_command
     when: condition

Here, condition represents the condition that determines whether the task should be executed or skipped.

  • Platform-Specific Tasks: Execute tasks that are specific to certain operating systems or distributions. For instance, install packages based on the OS type.
  • Idempotent Playbooks: Ensure tasks run only when necessary. Use “when” to check if a task is required before executing it, making playbooks idempotent.
  • Multi-Stage Deployments: Gradually roll out updates or changes across your infrastructure. Use “when” to control the deployment stage of specific hosts.
  • Dynamic Variable Assignment: Assign variables based on conditions, enhancing the adaptability of your playbooks.

Let’s take an example of a setup with an Ansible control node and two servers as shown below:

  • Rocky Linux 9                       IP: 192.168.1.5
  • Ubuntu 22.04                       IP: 192.168.1.2
  • Ansible control node           IP: 192.168.1.6

Using the Ansible control node which has already been set up and configured to communicate with the two servers.

The task at hand will be to install the Apache web server on both web servers using a single playbook.

But here’s the catch,

Installation of Apache on Rocky Linux, which is a Red Hat flavor,  differs from  Ubuntu, which is a Debian flavor. Both use different package managers and the Apache package also differs in both cases.  In such a scenario, where we have different variables at play, a conditional statement is crucial.

Given the differences mentioned,  we are going to use the ‘when’ conditional statement to install Apache web server as shown in the playbook as shown:

$ cat install_apache_httpd_server.yml
---
- name: install Apache Web-Server
hosts: all
tasks:
  - name: Install Apache on Rocky Linux Server
    dnf:
      name: httpd
      state: present
    become: yes
    when: ansible_os_family == "RedHat"
  - name: Install Apache2 on Ubuntu Server
    apt:
      name: apache2
      state: present
    become: yes
    when: ansible_os_family == "Debian"

When-Conditional-Ansible-Sample-Playbook

When you run this playbook, you’ll get the output below

Running-Ansible-Playbook-Install-Apache-Condition

Let’s break this down:

The first task or play executes the installation of the httpd package, colloquially known as the Apache web-server, on the remote Rocky Linux host using the dnf package manager which is the package manager for RHEL distros. Because we have defined all the host systems in our inventory, the installation of the httpd package alongside other dependencies will only take place for servers belonging to the Red Hat family.  This has been defined by the built-in variable ansible_os_family. In effect skips the installation on Ubuntu server, which is evidenced by the line “skipping [node2.example.com]

Because the Ubuntu server has been omitted in the first play, another play needs to be defined. The second play executes the installation of the Apache2 package using the apt package manager which is the native package manager for the Debian OS family. This implies that the apache2 package will be installed in all systems that fall under the Debian family, for which Ubuntu is a part.

Ultimately, the Apache Web Server will be installed on both  Red Hat and Debian based servers.

Using When Condition with the logical AND Operator

You can further refine your playbook and narrow it down to the specifics. Suppose you only want Ansible to install apache web server on Ubuntu servers whose version is 22.04, how would you go about it?

In this case, you will define another variable which will restrict the installation of Apache to Ubuntu servers on version 22.04. Here’s how they play would look like.

$ cat install_apache2_ubuntu.yml
---
- name: install Apache Web-Server
  hosts: all
  tasks:
  - name: Install Apache2 on Ubuntu Server
    apt:
      name: apache2
      state: present
    become: yes
    when: ansible_os_family == "Debian" and ansible_distribution_version == "22.04"

Install-Apache2-Ubuntu-22-04-Playbook

As you have seen, we have used the AND logical operator followed by another built-in Ansible variable known as ansible_distribution_version which has been assigned the value “22.04

For this play to be executed, both conditions have to be TRUE, i.e, the host system has to fall under the  Debian category of OS,  and the version has to be 22.04. As we know, only Ubuntu fits the description i.e Ubuntu 22.04.  If either of the conditions is not met, then the play fails and the installation of Apache will fail.

Apache2-Ubuntu-Ansible-playbook

Using When Condition with the logical OR Operator

With OR logical operator, the play will be executed when either or all of the conditions are satisfied.

Let’s consider another playbook:

$ cat check-disk-space.yml
---
- name: Playbook to Check Disk Space on Linux Servers
   hosts: all
   tasks:
   - name: Disk Space Usage Report on Servers
     shell: df -Th
     register: result

   - debug:
       var: result.stdout_lines
     when: Ansible_os_family == "Debian" or ansible_os_family == "RedHat"

Ansible-Conditional-Logical-or-Playbook

The above playbook displays disk usage metrics on servers in the setup that fall either under Debian or Red Hat distributions or both. Since both servers in our setup fall under the above-mentioned OS families, the playbook will display disk usage for both servers.

Run-Ansible-Playbook-Check-Disk-Space-Logical-OR

Conditional statements are essential in a multi-OS setup where variations exist in package management and server configuration. We hope you can now comfortably use the when conditional statement to perform various tasks according to the distribution of your server.

Conclusion

Mastering “when conditionals” in Ansible is a game-changer for your automation projects. It allows you to create dynamic and adaptable playbooks that respond intelligently to various scenarios. By harnessing the power of these conditionals, you’ll take your Ansible automation to the next level, streamlining tasks and ensuring precise control over your infrastructure.

Share Now!

Leave a Comment