$ ansible --version
ansible 2.10.8
I believe this is a different issue from Ansible's set_fact
not working at all.
I have the following variable defined in group_vars/all.yml
nexus_repo = "dev_builds"
nexus_url = "https://nexus.company.com/{{ nexus_repo }}"
Then on one of my tasks, I do
- name: Adjust nexus_repo value for release builds
set_fact:
nexus_repo: "release_builds"
nexus_url: "https://nexus.company.com/{{ nexus_repo }}"
- debug: msg="{{ nexus_url }}"
When I run my playbook (my-playbook.yml
runs my-role.yml
), I just see
$ ansible-playbook -i inverntories/hosts.yml -e var_hosts=my-host my-playbook.yml
TASK [my-role : Adjust nexus_repo value for release builds] ****************
ok: [10.227.x.x]
TASK [my-role : debug] *****************************************************
ok: [10.227.x.x] => {
"msg": "https://nexus.mycompany.com/repository/dev_builds"
}
Why is that?
The problem is that you can't re-use variables declared in the same set_fact. For example, if the variables nexus_repo and nexus_url are declared for the first time in the set_fact below. The task
- set_fact:
nexus_repo: release_builds
nexus_url: "https://nexus.company.com/{{ nexus_repo }}"
will fail because nexus_url can't use next_repo declared at the previous line:
The task includes an option with an undefined variable. The error was: 'nexus_repo' is undefined
This explains the 'strange' behavior you see when the group_vars/all.yml is used
shell> cat group_vars/all.yml
nexus_repo: dev_builds
nexus_url: "https://nexus.company.com/{{ nexus_repo }}"
The set_fact below will use the value dev_builds of the variable nexus_repo from group_vars/all.yml when evaluating nexus_url
- set_fact:
nexus_repo: release_builds
nexus_url: "https://nexus.company.com/{{ nexus_repo }}"
- debug:
var: nexus_url
gives
nexus_url: https://nexus.company.com/dev_builds
There are more options on how to fix it. For example, don't declare the same variable nexus_url twice
- set_fact:
nexus_repo: release_builds
- debug:
var: nexus_url
gives
nexus_url: https://nexus.company.com/release_builds
If you have to declare nexus_url new put it into the separate set_fact. For example, the tasks below give the same result
- set_fact:
nexus_repo: release_builds
- set_fact:
nexus_url: "https://nexus.company.com/{{ nexus_repo }}"
- debug:
var: nexus_url
See the Ansible issue Can't reference a dict key inside the same dict #50280.