Search code examples
ansibleansible-role

How to use a different entry point in ansible roles


Based on ansible documentation for roles I can make multiple role entry points by creating files:

playbooks/roles/my_role/tasks/main.yml
playbooks/roles/my_role/tasks/other.yml

And I can add the default main.yml role using this code:

---
- name: Example 1
  hosts: <hostnames>
  roles:
    - my_role

But how can I use the other.yml entrypoint?
I would expect it to be something like this, but none of those work:

---
- name: Example 1
  hosts: <hostnames>
  roles:
    - my_role:other
    - my_role/other
    - my_role.other

Solution

  • The roles directive in a playbook loads the default "entrypoint" of the role, i.e. tasks/main.yml. Other tasks files like tasks/others.yml can be loaded from it based on conditions, tags, etc.

    However if you do want to load a specific file from a role, you can use the include_role or import_role modules.

    E.g.:

      # invoke role's default "entrypoint" (main.yml)
      roles:
        - my_role
    
      tasks:
        # include the role, but tasks from other.yml
        - include_role:
            name: my_role
            tasks_from: other.yml
    

    Do note the order of execution mentioned in the documentation you linked.

    Another "hacky" option is to use include|import_tasks modules which works just like including a simple "tasks" file (losing the roles functionality), if it meets your requirement.

      tasks:
        - include_tasks: path/to/my_role/tasks/other.yml