Search code examples
ansibleansible-2.xansible-role

Print role name of the caller role in Ansible


How to print caller role name from within another role?

Playbook:

- name: print calling role name
  hosts: all
  tasks:
    - import_role:
        name: role2
        tasks_from: update

role2/tasks/update.yml:

- name: role 2
  import_role:
    name: role1
    tasks_from: update
  vars:
    role_scope: "{{ role_name }}"

role1/tasks/update.yml:

- name: role 1
  debug:
    msg: "Calling role: {{ role_scope }}"

Current output

Calling role: role1

Expected output

Calling role: role2

Solution

  • As pointed in the special variables page, there is a variable ansible_parent_role_names that contains a list of all the ancestor roles.

    When the current role is being executed by means of an include_role or import_role action, this variable contains a list of all parent roles, with the most recent role (in other words, the role that included/imported this role) being the first item in the list. When multiple inclusions occur, this list lists the last role (in other words, the role that included this role) as the first item in the list. It is also possible that a specific role exists more than once in this list.

    For example: When role A includes role B, inside role B, ansible_parent_role_names will equal to ['A']. If role B then includes role C, the list becomes ['B', 'A'].

    So, the solution is to use it in role1:

    - name: role 1
      debug:
        msg: "Calling role: {{ ansible_parent_role_names[0] }}"
    

    And if you want it to work whatever it is called by another role or not, you could do:

    - name: role 1
      debug:
        msg: >-
          Calling role: {{ ansible_parent_role_names[0] | default(role_name) }}
    

    This way, it will answer

    Calling role: role2
    

    When called via role2, but

    Calling role: role1
    

    when calling role1 directly in the playbook, for example.