diff --git a/changelogs/fragments/55152-add-more-info-to-AnsibleUndefinedVariable.yml b/changelogs/fragments/55152-add-more-info-to-AnsibleUndefinedVariable.yml new file mode 100644 index 00000000000..a229848bcbf --- /dev/null +++ b/changelogs/fragments/55152-add-more-info-to-AnsibleUndefinedVariable.yml @@ -0,0 +1,2 @@ +bugfixes: + - Provide more information in AnsibleUndefinedVariable (https://github.com/ansible/ansible/issues/55152) diff --git a/lib/ansible/template/vars.py b/lib/ansible/template/vars.py index 164cf1a1abe..464deecf808 100644 --- a/lib/ansible/template/vars.py +++ b/lib/ansible/template/vars.py @@ -104,8 +104,8 @@ class AnsibleJ2Vars(Mapping): value = None try: value = self._templar.template(variable) - except AnsibleUndefinedVariable: - raise + except AnsibleUndefinedVariable as e: + raise AnsibleUndefinedVariable("%s: %s" % (to_native(variable), e.message)) except Exception as e: msg = getattr(e, 'message', None) or to_native(e) raise AnsibleError("An unhandled exception occurred while templating '%s'. " diff --git a/test/integration/targets/template/runme.sh b/test/integration/targets/template/runme.sh index 61511ac82f1..8e21352d29b 100755 --- a/test/integration/targets/template/runme.sh +++ b/test/integration/targets/template/runme.sh @@ -22,3 +22,6 @@ ansible-playbook filter_plugins.yml -v "$@" # https://github.com/ansible/ansible/issues/68699 ansible-playbook unused_vars_include.yml -v "$@" + +# https://github.com/ansible/ansible/issues/55152 +ansible-playbook undefined_var_info.yml -v "$@" diff --git a/test/integration/targets/template/undefined_var_info.yml b/test/integration/targets/template/undefined_var_info.yml new file mode 100644 index 00000000000..b96a58db142 --- /dev/null +++ b/test/integration/targets/template/undefined_var_info.yml @@ -0,0 +1,15 @@ +- hosts: localhost + gather_facts: no + vars: + foo: [] + bar: "{{ foo[0] }}" + tasks: + - debug: + msg: "{{ bar }}" + register: result + ignore_errors: yes + + - assert: + that: + - '"foo[0]" in result.msg' + - '"object has no element 0" in result.msg'