ansible [core 2.16.3]
Today, from within a role, I tried to use set_fact to change a variable that had been passed to the role from a playbook using vars:.
Using -vv execution, the set_fact task to change the variable shows the correct value that I want set, but the value is not changed and changed: false is reported.
After some experimentation I think I understand this behavior: It seems that the calling playbook can set and modify the variable, but if you call a role and pass this variable using vars: then the role itself can only reference the variable but not change it. Assuming this is the intended behavior, we now accept it and appreciate it as a safe pattern.
If the role needs to manipulate the passed data, you just use set_fact to copy the value from a passed role into a new variable and manipulate that variable from within the role. This way this modified variable is scoped within the role and doesnât impact the playbookâs use of the variable after the role is done executing. Right?
What Iâm requesting is pointers to documentation so I can understand this authoritatively and set coding policy on more than just my current observations and interpretations. Thanks!
Simulated Playbook (code not tested):
- name: Set config value
ansible.builtin.set_fact:
my_role_config:
- apple
- banana
- apple
- blueberry
- apple
- name: Include modular role
ansible.builtin.include_role:
name: my_role
tasks_from: main.yml
vars:
my_role_config: "{{ my_role_config }}"
Role tasks/main.yml:
---
- name: Initial value of my_role_config
ansible.builtin.debug:
var: my_role_config
- name: Immediately change the incoming value
ansible.builtin.set_fact:
my_role_config: "{{ my_role_config | unique }}"
- name: Show my_role_config made unique
ansible.builtin.debug:
var: my_role_config
Simulated output looks something like this:
- Task within role shows it would have set only unique list values
- Debug statement immediately following shows the variable did not change at all
TASK [...: Initial values of my_role_config]
ok: [hostname.mycompany.com] =>
ansible_facts:
my_role_config:
- apple
- banana
- apple
- blueberry
- apple
TASK [..: Immediately change the incoming value]
ok: [lnxdocstageftden01.pinnacol.com] =>
ansible_facts:
my_role_config:
- apple
- banana
- blueberry
changed: false
TASK [...: Show my_role_config made unique]
ok: [hostname.mycompany.com] =>
ansible_facts:
my_role_config:
- apple
- banana
- apple
- blueberry
- apple