Reputation: 3478
In a role, I am trying to load some variables from another role. (If that role was included in the current play, the variables would be accessible, but it's not so they're not.)
So I tried this:
- include_vars: ../../another_role/defaults/main.yml
But it doesn't work, no error but the variables are still undefined.
So I tried to be smart and symlink the file to vars/another_role_defaults.yml
in the role where I want to use the vars and then include it like this:
- include_vars: another_role_defaults.yml
Same result, no error (why doesn't it throw an error if the file cannot be found??) but variables are still undefined. I tried this as well, for good measure, but still no cigar.
- include_vars: ../vars/another_role_defaults.yml
What am I doing wrong?
Upvotes: 14
Views: 32795
Reputation: 1250
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
Upvotes: 2
Reputation: 9515
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
Upvotes: 4
Reputation: 3478
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
Upvotes: 17