Level 1
0 / 100 XP

Ansible Conditional Statements

In this lesson, you will learn how to create and run a new Ansible playbook that will demonstrate the use of boolean variables and conditional statements.

By the end of this lesson, you'll understand how to control the execution of tasks based on the value of a boolean variable.

Creating the Playbook with Boolean Variable

Start by creating a new playbook file named conditional_test.yml.

nano conditional_test.yml

In this playbook, we will target all hosts and define a boolean variable create_file at the top, which will control whether a file should be created or removed.

Text
--- - hosts: all vars_files: - secret.yml vars: create_file: True tasks:

Let's add a debug message that will show the value of our variable create_file:

Text
- name: Should the file exist? debug: msg: "File should exist: {{ create_file }}"

Next, add a task to create the file conditional_test_file.txt in the home directory when create_file is true:

Bash
- name: Create the file file: path: ~/conditional_test_file.txt state: touch when: create_file == True

This task uses the file module to create a file, and it executes when create_file is true (yes). The state: touch parameter ensures that the file is created if it doesn't exist.

Now, let's add a task to remove the file if create_file is false:

Text
- name: Remove the file file: path: ~/conditional_test_file.txt state: absent when: not create_file == True

This task also uses the file module but with state: absent to remove the file if it exists. It executes when create_file is false (no).

Running the Playbook

With the playbook ready, you can execute it to see the conditional logic in action. To test both conditions, first run the playbook with…