Applying Ansible When Condition
Now that you understand the basics of Ansible's when
condition, let's dive deeper into how to apply it in your Ansible playbooks.
Conditional Expressions
The when
condition supports a variety of expressions, including:
- Comparison operators (==, !=, >, <, >=, <=)
- Boolean operators (and, or, not)
- Membership tests (in, not in)
- Regex matching (match)
Here's an example that uses multiple conditions:
- name: Install package
apt:
name: nginx
state: present
when:
- ansible_distribution == 'Ubuntu'
- ansible_distribution_version is version('20.04', '>=')
In this example, the task will only be executed if the system is running Ubuntu and the version is 20.04 or later.
Accessing Variables and Facts
You can use variables and facts within your when
conditions to make them more dynamic and flexible. For example:
- name: Install package
apt:
name: "{{ package_name }}"
state: present
when: package_name is defined
In this example, the task will only be executed if the package_name
variable is defined.
Combining Conditions
You can also combine multiple conditions using the and
, or
, and not
operators. For example:
- name: Restart service
systemd:
name: nginx
state: restarted
when:
- ansible_service_mgr == 'systemd'
- nginx_config_changed | default(false)
In this example, the task will only be executed if the system is using systemd and the nginx_config_changed
variable is true (or if the variable is not defined).
By leveraging the power of Ansible's when
condition, you can create more robust and adaptable playbooks that can handle a wide range of scenarios.