In this lab, you will learn how to use conditionals in an Ansible playbook. Specifically, you will understand how the when clause can be used to control the execution of tasks based on the value of a variable.
- Learn how to use the
whenclause to implement conditionals. - Create a task that executes only under specific conditions.
- Basic understanding of Ansible playbooks.
- Ansible installed on your ansible machine.
- Access to target hosts in your inventory.
Estimated Time: 20 minutes
-
Create a new YAML file named
conditional_playbook.yml. -
Define the play's name, target hosts (
allin this case), and whether to gather facts:--- - name: A conditional play hosts: all gather_facts: no
Explanation:
hosts: alltargets all hosts in the inventory.gather_facts: noskips automatic fact gathering to keep the playbook simple.
-
In the
varssection, define a variable namedepicand assign it a boolean value:vars: epic: true
Explanation:
- The variable
epicwill be used to control the execution of tasks.
- The variable
-
Under the
taskssection, add a task that prints a message "Hello A" if the variableepicistrue:tasks: - name: Task A debug: msg: "Hello A" when: epic
Explanation:
- The
whenclause ensures the task runs only when the condition (epic: true) is met.
- The
-
Save the
conditional_playbook.ymlfile. -
Run the playbook using the following command:
ansible-playbook conditional_playbook.yml
-
Observe the output. The task "Task A" will execute only if
epicis set totrue.
In this lab, you've learned how to use conditionals in Ansible playbooks, progressing from simple boolean checks to complex production-ready logic.
What you learned:
- Basic
whenclause usage - OS-specific conditional logic
- Environment-based configurations
- Complex multi-condition logic
- Real-world business logic implementation
Key Conditional Patterns:
- Single condition:
when: variable - Multiple conditions:
when: condition1 and condition2 - List conditions:
when: variable in ["value1", "value2"] - Complex logic:
when: (condition1 or condition2) and condition3
These patterns form the foundation for building sophisticated, environment-aware automation! 👏