Role defaults available in another role's scope

I noticed that defaults specified in one role’s scope become available in a second role’s scope if both roles are part of the same playbook. I wonder why these defaults do not stick to their role scope?

Sample:

role_1/defaults/main.yml:
snaap: true

role_2/tasks/main.yml:

- name: debug
  ansible.builtin.debug: "{{ snaap }}"

playbook.yml:

- role: role_1
  tags: [role1]
- role: role_2
  tags: [role2]

I run:
ansible-playbook playbook.yml --tags role2

result:

TASK [role_2 : debug] ***
ok:
msg: true   # even though not defined in role_2

A nice extra is that if you define in role_2/defaults/main.yml:
snaap: "{{ snaap }}"

you get a nice infinite recursion error :slight_smile:

@bluppfisk Hello.

You can change DEFAULT_PRIVATE_ROLE_VARS to True to be private.

https://docs.ansible.com/ansible/latest/reference_appendices/config.html#default-private-role-vars

If change by Environment Variable

% ANSIBLE_PRIVATE_ROLE_VARS=True ansible-playbook -i localhost, playbook.yml  --tags role2

PLAY [test] ****************************************************************************************************************************************************************************************

TASK [role_2 : debug] ***************************************************************************************************************************************************************************
fatal: [localhost]: FAILED! => {
    "msg": "The task includes an option with an undefined variable. The error was: 'snaap' is undefined.(omit)
2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.