Include vars in role tasks

The accepted solution did not work in my case in case a file is imported from another role. A slightly modified approach via special variable which worked for me:

- include_vars: "{{ role_path }}/../another_role/defaults/main.yml"
  tags: foo

role_path - The path to the dir of the currently running role


It was my own fault in the end... I tested this by using the debug module and tags like this:

- include_vars: ../../another_role/defaults/main.yml

- debug: msg={{ variable }}
  tags: foo

and then executing the playbook like this:

  ansible-playbook -vvvv playbook.yml --tags foo

Once I left out the tags, it works (of course). The problem was that I should have added the tags to the include_vars command as well like this:

- include_vars: ../../another_role/defaults/main.yml
  tags: foo

- debug: msg={{ variable }}
  tags: foo

As of ansible-core 2.11 you can do this:

- include_vars: ../../nrpe/vars/standard_nrpe_checks.yml
  name: standard_nrpe_checks
- debug:
    msg: "{{ standard_nrpe_checks }}"

To get the same result you can also use set_fact with the lookup plugin.

- debug:
    msg: "{{ lookup('file', '../../nrpe/vars/standard_nrpe_checks.yml') }}"

I wanted to mention if you're using collections and distributing a playbook you can use

playbooks
  |_vars/
    |_standard_nrpe_checks.yml

In this instance I'm now able to share vars from within a collection and since it's in the lookup path I don't need to specify it relatively. I.e. instead of having a list be an nrpe role default read it in for both roles and maintain it in one place.

- include_vars: standard_nrpe_checks.yml
  name: standard_nrpe_checks
- debug:
    msg: "{{ standard_nrpe_checks }}"
TASK [namespace.my_collection.icinga : debug] *******************************************
ok: [hostname] =>
  msg: |-
    standard_nrpe_checks:
      check_users:
        script: check_users