I have the following roles
structure:
$ tree roles
roles
├── user
│ └── tasks
│ └── main.yaml
└── validation
└── tasks
└── main.yaml
My goal is to include the validation
role into multiple roles and avoid using a when
condition, into every task.
validation/tasks/main.yaml
:
---
- name: Test model
ansible.builtin.command: grep 'Debian' /proc/device-tree/model
changed_when: false
register: model
- name: Set fact
ansible.builtin.set_fact:
debian: true
when: model.rc == 0
user/tasks/main.yaml
:
---
- name: Perform validation
ansible.builtin.include_role:
name: validation
- name: Get user info
ansible.builtin.user:
name: user
state: present
register: user_info
when: debian | default(false)
playbook.yaml
:
---
- name: Deployment
hosts: cluster
become: true
gather_facts: true
roles:
- role: user
When I run the playbook, everything works as expected. My goal is to avoid adding inside each task that when
condition.
Is there a way to create a handler which will perform automatically a validation for each role task? The above example is very limited, the actual playbook contains many roles, with each task being required to be validated.
My end-result should be:
roles:
- role: user
- role: os
- role: reset
...
Where each role task would automatically perform a validation during execution. Thank you for your help.
3
Answers
I resolved the issue, by including the
validation
role intometa
.user/meta/main.yaml
:You may try using when condition in role modifying playbook.yaml like this using any variable you may need in when condition:
For more information check ansible documentation here:
https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_conditionals.html#conditionals-with-roles
Also if you need this, in playbook.yaml you may set any variables needed for a role to run.
The validation is not needed. Use Ansible variable ansible_os_family instead. See gather_facts. For example,
gives
You want to perform a role for multiple operating systems (or families of OS). In this case, you have to decide where to place the conditions.
a) If you want to use the
role
keyword you have to place the conditions inside the roles because the facts will be gathered after the roles are loaded. In other words, the variable ansible_os_family won’t be available before a role is loaded.For example, create role
user
Then, the playbook
gives
b) If you want to use the module
include_role
the situation is more flexible. For example, you can create roles for particular OS familiesDeclare the variables, for example in group_vars/all
Then, the playbook
gives
Notes:
See available platforms
See other distribution facts, for example