Skip to content

Role Tricks

Matt DePorter edited this page Aug 13, 2018 · 3 revisions

Runnning playbooks in role and in ansible root

This allows the playbook to reside inside the role/<role-name> directory. In this example, we are using the role-name role to do this.

First need a set_fact to remap {{ playbook_dir }}:

  pre_tasks:

    # Workaround to run playbook inside this role
    - name: set playbook dir when running this playbook here
      set_fact:
        ansible_root_dir: "{{ playbook_dir | regex_replace('/roles/role-name', '') }}"
        role_name_path: "{{ playbook_dir }}/../../roles/role-name/tasks/main.yaml"
      when: "'/roles/role-name' in playbook_dir"

Make some defaults to override by default in defaults/main.yml:

# Workarounds for running the playbook in this role
ansible_root_dir: "{{ playbook_dir }}"
ansible_root_dir_roles_path: "{{ ansible_root_dir }}/roles"

After the ansible_root_dir has been set to take place of {{ playbook_dir }}, swap out all paths for {{ ansible_root_dir }} instead.

If there is an include: statement, default it to the root of the role's tasks/*.yaml directory. E.g.

- include: "{{ role_name_path | default('../../role-name/tasks/main.yaml') }}"
  when: flag1 | bool and flag2 | bool