diff --git a/changelogs/fragments/71214-add-vars-variable-for-delegated-vars.yaml b/changelogs/fragments/71214-add-vars-variable-for-delegated-vars.yaml new file mode 100644 index 00000000000..6bcdeaa3e63 --- /dev/null +++ b/changelogs/fragments/71214-add-vars-variable-for-delegated-vars.yaml @@ -0,0 +1,2 @@ +bugfixes: + - VariableManager - Add the 'vars' key before getting delegated variables (https://github.com/ansible/ansible/issues/71092). diff --git a/lib/ansible/vars/manager.py b/lib/ansible/vars/manager.py index a4942bac5d3..346270b7f91 100644 --- a/lib/ansible/vars/manager.py +++ b/lib/ansible/vars/manager.py @@ -426,16 +426,16 @@ class VariableManager: if task: all_vars['environment'] = task.environment - # if we have a task and we're delegating to another host, figure out the - # variables for that host now so we don't have to rely on hostvars later - if task and task.delegate_to is not None and include_delegate_to: - all_vars['ansible_delegated_vars'], all_vars['_ansible_loop_cache'] = self._get_delegated_vars(play, task, all_vars) - # 'vars' magic var if task or play: # has to be copy, otherwise recursive ref all_vars['vars'] = all_vars.copy() + # if we have a task and we're delegating to another host, figure out the + # variables for that host now so we don't have to rely on hostvars later + if task and task.delegate_to is not None and include_delegate_to: + all_vars['ansible_delegated_vars'], all_vars['_ansible_loop_cache'] = self._get_delegated_vars(play, task, all_vars) + display.debug("done with get_vars()") if C.DEFAULT_DEBUG: # Use VarsWithSources wrapper class to display var sources diff --git a/test/integration/targets/delegate_to/resolve_vars.yml b/test/integration/targets/delegate_to/resolve_vars.yml new file mode 100644 index 00000000000..898c0b0ad04 --- /dev/null +++ b/test/integration/targets/delegate_to/resolve_vars.yml @@ -0,0 +1,16 @@ +--- +- name: though we test for 'vars' this is only for backwards compatibility and the 'vars' variable will be deprecated and removed in the future + hosts: localhost + gather_facts: no + tasks: + - add_host: + name: host1 + ansible_connection: local + +- hosts: localhost + gather_facts: no + vars: + server_name: host1 + tasks: + - command: echo should delegate to host1 with local connection + delegate_to: "{{ vars['server_name'] }}" diff --git a/test/integration/targets/delegate_to/runme.sh b/test/integration/targets/delegate_to/runme.sh index 5e08f5c36a7..6b9d59938e2 100755 --- a/test/integration/targets/delegate_to/runme.sh +++ b/test/integration/targets/delegate_to/runme.sh @@ -71,3 +71,5 @@ ln -s python secondpython ) ansible-playbook verify_interpreter.yml -i inventory_interpreters -v "$@" ansible-playbook discovery_applied.yml -i inventory -v "$@" + +ansible-playbook resolve_vars.yml -i inventory -v "$@"