One of the core features of Ansible is conditional task execution. This provides us with the ability to control which tasks to run on a given host based on a condition/test that we specify. In this recipe, we will outline how to configure conditional task execution.
Using Ansible's conditionals
Getting ready
In order to follow along with this recipe, an Ansible inventory file must be present and configured as outlined in the previous recipes. Furthermore, the Ansible variables for all our hosts should be defined as outlined in the previous recipes.
How to do it...
- Create a new playbook called ansible_cond.yml inside the ch1_ansible folder.
- Place the following content in the new playbook as shown here:
---
- name: Using conditionals
hosts: all
gather_facts: no
tasks:
- name: Run for Edge nodes Only
debug:
msg: "Router name is {{ hostname }}"
when: "'edge' in group_names"
- name: Run for Only MX1 node
debug:
msg: "{{ hostname }} is running {{ os }}"
when:
- inventory_hostname == 'mx1'
- Run the playbook as shown here:
$ ansible-playbook -i hosts ansible_cond.yml
How it works...
Ansible uses the when statement to provide conditional execution for the tasks. The when statement is applied at the task level and if the condition in the when statement evaluates to true, the task is executed for the given host. If false, the task is skipped for this host. The output as a result of running the preceding playbook is shown here:
The when statement can take a single condition as seen in the first task, or can take a list of conditions as seen in the second task. If when is a list of conditions, all the conditions need to be true in order for the task to be executed.
See also...
For more information regarding Ansible's conditionals, please check the following URL:
https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html