Ansible RHCE Ansible Series

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.

Ahmed Alkabary
Ahmed Alkabary

Table of Contents

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
    - name: Detect Ubuntu Servers
        msg: "This is an Ubuntu Server."
      when:  ansible_facts['distribution'] == "Ubuntu"

Now go ahead and run the playbook:

This post is for members only

Already have an account? Sign in