How to Use When Condition in Ansible Playbook (Examples)

In this guide, we will explain how to use when condition in Ansible Playbook (Examples).

Ansible is a powerful automation tool used to configure systems, deploy software, and orchestrate IT environments. One of its most useful features is the when condition, which allows you to control the execution of tasks based on specific criteria.

What is the when Condition in Ansible?

The when condition in Ansible is used to control whether a task or a role should be executed. It evaluates an expression and runs the task only if the condition evaluates to true. This allows you to skip certain tasks based on the state of a variable or the result of a previous task. 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"

Use When Condition in Ansible 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"

When Condition with the logical OR Operator

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

The when condition in Ansible gives you granular control over task execution, making your playbooks more efficient and adaptable. Whether you’re checking operating systems, variable states, or results from previous tasks, the when condition adds a layer of flexibility to your automation.

Key Takeaways:

  • Use the when condition to control task execution based on variables, facts, or expressions.
  • Combine multiple conditions with and and or to create complex logic.
  • You can check the result of previous tasks or use loops with the when condition for dynamic task control.

By mastering the when condition, you can write more intelligent and dynamic Ansible playbooks that respond to the specific needs of your infrastructure.

Leave a Comment

Your email address will not be published. Required fields are marked *