Apr 23, 2021 13 min read

RHCE Ansible Series #6: Decision Making in Ansible

This is the sixth chapter of RHCE Ansible EX 294 exam preparation series. Learn about using conditional statements in Ansible.

In this tutorial, you will learn how to add decision making skills to your Ansible playbooks.

You will learn to:

  • Use when statements to run tasks conditionally.
  • Use block statements to implement exception handling.
  • Use Ansible handlers to trigger tasks upon change.

Needless to say that you should be familiar with Ansible playbooks, ad-hoc commands and other Ansible basics to understand this tutorial. You may follow the earlier chapter of this RHCE Ansible series.

This tutorial follow the same setup that was mentioned in the first chapter of this series: 1 Red Hat control, 3 CentOS nodes and 1 Ubuntu node.

Choosing When to Run Tasks

Let's start to put conditions on when to run a certain task with Ansible.

Using when with facts

You can use when conditionals to run a task only when a certain condition is true. To demonstrate, create a new playbook named ubuntu-server.yml that has the following content:

[[email protected] plays]$ cat ubuntu-server.yml 
---
- name: Using when with facts 
  hosts: all
  tasks:
    - name: Detect Ubuntu Servers
      debug:
        msg: "This is an Ubuntu Server."
      when:  ansible_facts['distribution'] == "Ubuntu"

Now go ahead and run the playbook:

Read the full story

The rest of the article is available to LHB members only. You can sign up now for FREE to read the rest of this article along with access to all members-only posts. You also get subscribed to our fortnightly Linux newsletter.

Subscribe
Already have an account? Sign in
Great! You’ve successfully signed up.
Welcome back! You've successfully signed in.
You've successfully subscribed to Linux Handbook.
Your link has expired.
Success! Check your email for magic link to sign-in.
Success! Your billing info has been updated.
Your billing was not updated.