Introduction
In Ansible, conditional statements are a cornerstone of efficient and dynamic playbooks. They enable you to control task execution based on specific criteria, ensuring that only relevant actions are performed. This article explores the when clause, showcasing how conditionals can streamline automation workflows.
What are Conditionals in Ansible?
Conditionals allow you to execute tasks only when certain conditions are met. This is achieved using the when keyword, which evaluates a condition and determines whether the task should run.
Basic Syntax
``yaml
- name: Install package only on RedHat systems
yum:
name: httpd
state: present
when: ansible_facts.os_family == "RedHat"
`
In this example, the task runs only if the operating system family is RedHat.
---
Common Use Cases for Conditionals
1. Operating System Checks
Conditionals are often used to execute tasks specific to an operating system.
#### Example:
`yaml
- name: Install Apache on Debian-based systems
apt:
name: apache2
state: present
when: ansible_facts.os_family == "Debian"
`
Use Case:
- Ensures tasks are executed only on compatible systems, avoiding unnecessary or conflicting actions.
---
2. Variable Validation
Conditionals can check if a variable is defined or has a specific value.
#### Example:
`yaml
- name: Proceed only if the user variable is defined
debug:
msg: The user variable is set
when: user is defined
`
Use Case:
- Avoids errors in playbooks by verifying variable existence or value before execution.
---
3. Combining Multiple Conditions
You can combine multiple conditions using logical operators like and and or.
#### Example:
`yaml
- name: Install software if the system is RedHat and memory is sufficient
yum:
name: httpd
state: present
when: ansible_facts.os_family == "RedHat" and available_memory_mb > 1024
`
Use Case:
- Enforces complex preconditions for task execution.
---
Advanced Techniques with Conditionals
1. Using Loops with Conditions
Combine loops and conditions to refine task execution within a set of items.
#### Example:
`yaml
- name: Restart services if enabled
service:
name: item
state: restarted
when: item_enabled
with_items:
- item1
- item2
- item3
`
Use Case:
- Dynamically restart only the services that are enabled.
---
2. Conditional Includes
You can include tasks, files, or roles conditionally to modularize playbooks.
#### Example:
`yaml
- name: Include tasks based on OS
include_tasks: redhat.yml
when: ansible_facts.os_family == "RedHat"
`
Use Case:
- Creates modular and reusable playbooks tailored for specific environments.
---
3. Checking Facts and Metadata
Leverage system facts and metadata to conditionally execute tasks.
#### Example:
``yaml
- name: Run task only on virtual machines
debug:
msg: This is a virtual machine
when: ans