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.
Let's add a debug message that will show the value of our variable create_file:
Next, add a task to create the file conditional_test_file.txt in the home directory when create_file is 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:
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…
No comments yet. Add the first comment to start the discussion.