How to Work with Ansible When and Other Conditionals

choubertsprojects

VPN offers!

1. NordVPN

2. Surfshark

3. ExpressVPN

ansible is a configuration management and provisioning tool that can be used for application deployment, system administration tasks and more. This tutorial will cover how to work with conditionals in ansible when working on your playbook.

Ansible is a configuration management tool. It can be used to configure systems and applications. The “ansible if else condition” allows users to control what happens when multiple conditions are met.

How to Work with Ansible When and Other Conditionals

You’re in for a treat if you need to run Ansible jobs depending on various criteria. Ansible’s when and other conditionals allow you to analyze circumstances such as whether or not a task is reliant on another.

In this video, you’ll learn how to use Ansible’s when and other conditionals to complete tasks without causing problems.

Let’s get started!

Prerequisites

This lesson includes practical examples. If you want to join in, make sure you have the following items:

Related: Ansible Setup Guide (Ubuntu, RHEL, CentOS, macOS)

  • To execute commands, you’ll need a remote computer.
  • You’ll need to create an inventory file and configure one or more hosts to execute Ansible commands and playbooks. The tutorial will utilize the online inventory group.

Working with Ansible in a Playbook with Multiple Tasks

When several jobs in a playbook run without particular requirements, it might be a pain. Let’s start by creating Ansible when conditions in an Ansible playbook with several jobs.

1. Log in to the Ansible controller host using a terminal.

2. In your home directory, run the instructions below to create a directory and name it anything you like, then move to that directory.

The directory for this example is called ansible when condition demo. The playbook you’ll use to activate the when condition inside the Ansible job will be in this directory.

# Create the /ansible when condition demo directory. /ansible when condition demo/mkdir # Change to /ansible when condition demo as the working directory. cd /ansible when condition demo/ansible when condition demo

3. Create a YAML file in the /ansible when condition demo directory using your favourite code editor. My playbook.yml is the name of the file in this example. Copy and paste the text of the YAML playbook below into the my playbook.yml file.

The when conditions in both Task-1 and Task-2 examine the operating system each remote host is running. On each task, the result is provided to the ansible os family placeholder variable.

If the value of the ansible os family placeholders is RedHat or Debian, Ansible will run any of the tasks to install Apache.

—- – name: Ansible tasks to be used with Ansible When # Specifying the remote server on which Ansible will be installed hosts: web remote user: ubuntu # Using Ubuntu as Remote Host: true # Execute the tasks as a superuser (sudo): # (Task-1) Installs Apache on Remote Node if ansible os family == “RedHat” – name: Install Apache on CentOS Server yum: name=httpd state=present when ansible os family == “RedHat” # becomes: yes (Task-2) Installs Apache on Remote Node if ansible os family == “Debian” – name: Install Apache on Ubuntu Server apt:name=apache2 state=present when ansible os family == “Debian” become: yes

4. Now run the ansible-playbook command to perform the tasks indicated in the playbook (my playbook.yml) on the remote host specified in your inventory file.

my playbook.yml ansible-playbook

As you can see in the image below:

  • The first TASK returned an OK result, indicating that no adjustments are required.
  • The skip status was returned by the second TASK. The job will be skipped if the condition is not satisfied.
  • The third TASK returned a changed status, indicating that the remote host wasn’t in the right condition (i.e., Apache wasn’t installed) and needed to be adjusted to install Apache.

Using the ansible-playbook command to start the ansible-playbook Using the ansible-playbook command to start the ansible-playbook

5. Use your preferred SSH client to connect to the remote server that was the Ansible playbook’s target and check that Apache is installed and working.

6. Finally, execute the service command below to see whether Apache is installed on the remote server (status apache2).

You’ve installed Apache service on the remote system, as seen below.

Verifying the remote node's Apache service Verifying the remote node’s Apache service

When and loops when using Ansible

Ansible tasks were previously done according to an Ansible when for a certain parameter, such as ansible os family. However, you may need to verify a condition that has several arguments in a list. If that’s the case, consider including a loop in a task.

Open the my_playbook.yml file you previously created (step three under the “Working with Ansible in a Playbook with Multiple Tasks”). Replace the content of the my_playbook.yml file with the code below.

The task (Task-1) in the code below executes a loop that checks whether the item value is larger than five and returns the result.

— – name: Ansible tasks to work on Ansible When # Defining the remote server where Ansible will run hosts: web remote_user: ubuntu # Using Remote host as ubuntu become: true tasks: # (Task -1) Checking if item value is greater than 5 – name: Run with items greater than 5 ansible.builtin.command: echo {{ item }} loop: [ 0, 2, 4, 6, 8, 10 ] when: item > 5*

Now, as before, run the command below to execute the playbook.

my playbook.yml ansible-playbook

When the condition is false, the task returns skipping status, and when the condition is true, the task returns altered status.

Using numerous factors to check the when condition Using numerous factors to check the when condition

When to use Ansible and Ansible facts

You may wish to use numerous criteria to complete a job. If that’s the case, understand how to use Ansible facts in the when condition. You may use Ansible facts to create a conditional statement to perform tasks depending on gathered facts like your operating system, IP addresses, associated file systems, and more.

Replace the code in my playbook.yml with the following code.

Both tasks (Task-1 and Task-2) in the code below only run (system shutdown) if one of the following criteria is true:

  • The distribution and distribtion major version variables both returned true.
  • The value for os family is CentOS.

—- – Ansible’s name When Web remote user: ubuntu single task example # (Task-1): Shut down the remote node if the distribution is CentOS with a major upgrade Version 6 – ansible.builtin.command: /sbin/shutdown -t now when: – ansible facts[‘distribution’] == “CentOS” – ansible facts[‘distribution major version’] == “CentOS” # (Task-2): If os family is CentOS, stop the remote node. – name: Turn off CentOS-based systems when: ansible facts[‘os family’] == “CentOS” ansible.builtin.command: /sbin/shutdown -t

Execute the playbook in the same way you executed the command below.

my playbook.yml ansible-playbook

Because you’re on Ubuntu, both tasks display the skipping status below. If you’re using CentOS, the job will only run.

When using Ansible, execute the ansible-playbook using Ansible facts. When using Ansible, execute the ansible-playbook using Ansible facts.

Working with Ansible when Registered Values are Used

You may wish to perform or skip a job in a playbook depending on the result of a previous task. For example, following a prior task upgrade, you could wish to setup a service. Use a registered variable in such scenario. A registered variable enables you to save the result of a previous operation as a variable and use it as an input for the future activity.

1. Make a directory called /home/ubuntu/hello in your home directory.

2. Replace the text of my playbook.yml with the code below, which does the following:

The first job (Task-1) lists the contents (files and subdirectories) of the /etc/hosts directory in memory and uses the register command to store the result to the contents1 variable.

The second job (Task-2) memorizes the contents of the /home/ubuntu/hello directory (which is now empty) and stores it to the contents2 variable.

If either the registered result for the contents1 or contents2 variable is empty, the third task (Task-3) checks and outputs a “Directory is empty” message.

The shell output from performing the task commands is preserved in the stdout property of the contents1 and contents2 variables.

—- – Ansible’s name When hosting a single job, for example, web remote user: ubuntu # (Task-1): To list the directory content in the /etc/hosts directory – name: List contents of directory and Store in content1 ansible.builtin.command: ls /etc/hosts register: contents1 # (Task-2): To list the directory content in the /etc/hosts directory – name: List contents of directory and Store in content1 ansible. To list the contents of the directory /home/ubuntu/hello – name: # (Task-3): Display Directory is empty if either of the following directories are empty: # /etc/hosts or /home/ubuntu/hello directory – name: Check contents for emptiness for content1 or content2 ansible.builtin.debug: msg: “Directory is empty” when: contents1.stdout == “” or contents2.stdout == “”

3. Finally, use the ansible-playbook command to run the playbook.

my playbook.yml ansible-playbook

The third task produces the Directory is empty message because the registered result for the contents2 variable is empty, as seen below.

When depending on registered values, run the Ansible playbook for Ansible. When depending on registered values, run the Ansible playbook for Ansible.

When in Ansible Roles, working with Ansible

You’ll discover how Ansible operates inside Ansible roles in this last example. Ansible roles enable you to reuse common setups and deploy faster. Continue reading to find out how a task only calls Ansible roles if the Ansible when condition is true.

Understanding and Configuring Ansible Roles (Tutorial)

1. In your home directory, use the commands below to create a directory called /ansible role when demo and set it as the working directory. The demo files for this example may be found in the /ansible role when demo directory.

# Make a directory in your home directory called /ansible role when demo. /ansible role when demo mkdir # Navigate to /ansible role when demo. /ansible role when demo cd

2. Create a /ansible role when demo/roles and /ansible role when demo/roles/java/tasks directory using the instructions below.

The following are the contents of each directory:

  • The role you need to deploy is located in the /ansible role when demo/roles directory.

By default, Ansible searches for roles in one of two places: the roles/ directory inside the playbook directory, or the /etc/ansible/roles directory. Declare the pathways using the – role: argument in the playbook if you want to store roles at separate paths.

  • The main.yml file you’ll need to deploy a role can be found in the /ansible role when demo/roles/java/tasks folder.

# mkdir -p roles create a directory called roles within the /ansible role when demo directory # Change to the /ansible role when demo/roles directory using cd roles. # Mkdir -p java/tasks creates the parent (-p) directory java and a subfolder tasks.

Now, under the /ansible role when demo/roles/java/tasks directory, create a file titled main.yml, and copy and paste the playbook code below into it.

The apt module is used in the plan below to install Java on the remote node.

How to Manage Linux Packages Using the Ansible apt Module

—- # Java installation (Open Jdk) – name: apt: name=openjdk-8-jdk Install Java 1.8

4. Create a new YAML file with a different name and copy/paste the code below. The file is titled /ansible role when demo/java-setup.yml in this example.

When the remote user (ubuntu) is on Debian OS, the code below deploys the Ansible role (java) to the remote user (ubuntu).

– name: Java Installation Playbook hosts: myserver remote user: ubuntu # Using ubuntu as the remote user: genuine tasks: roles: – role: java # Only run the job if remote user is running Debian. ansible facts when ‘Debian’ == ‘os family’

5. Verify that all essential folders and files exist in the /ansible role when demo directory using the tree command.

Verifying that the /ansible role when demo directory has all of the needed directories Verifying that the /ansible role when demo directory has all of the needed directories

6. Finally, use the ansible-playbook command to run the playbook. java-setup.yml ansible-playbook

java-setup.yml ansible-playbook

Below, the task returned a changed status, indicating Java has been installed successfully as the remote node is on a Debian OS. Untitled When utilizing Ansible roles, you may run the Ansible playbook.

When utilizing Ansible roles, you may run the Ansible playbook. When utilizing Ansible roles, you may run the Ansible playbook.

Conclusion

You learnt numerous methods to use Ansible when and other conditionals in this lesson. From simple operations like using Ansible facts and installing Ansible roles, you’ve learnt how to apply Ansible when conditions.

What would you do with this newfound information now? Perhaps use Ansible templates to configure many servers while applying Ansible when conditions?

Related:How to Save Configuration Time with Ansible Templates

Ansible is a command-line tool that can be used to automate tasks. In this blog, we will learn how to use Ansible when and other conditionals. Reference: ansible when string contains.

Related Tags

  • ansible conditional variable
  • ansible when not equal
  • ansible when variable is defined
  • ansible when true
  • ansible when in list