Search code examples
ansibleansible-role

Avoid using when condition for each task, while including an Ansible validation role?


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.


Solution

  • I resolved the issue, by including the validation role into meta.

    user/meta/main.yaml:

    ---
    dependencies:
      - role: validation