diff --git a/changelogs/fragments/55113-template-lookup-restore-vars.yaml b/changelogs/fragments/55113-template-lookup-restore-vars.yaml new file mode 100644 index 0000000000..259d00603a --- /dev/null +++ b/changelogs/fragments/55113-template-lookup-restore-vars.yaml @@ -0,0 +1,2 @@ +bugfixes: + - template lookup - restore variables between calls (https://github.com/ansible/ansible/issues/55113) diff --git a/lib/ansible/plugins/lookup/template.py b/lib/ansible/plugins/lookup/template.py index 6b00e8ebc8..959a2c096e 100644 --- a/lib/ansible/plugins/lookup/template.py +++ b/lib/ansible/plugins/lookup/template.py @@ -45,6 +45,7 @@ _raw: description: file(s) content after templating """ +from copy import deepcopy import os from ansible.errors import AnsibleError @@ -67,6 +68,8 @@ class LookupModule(LookupBase): variable_start_string = kwargs.get('variable_start_string', None) variable_end_string = kwargs.get('variable_end_string', None) + old_vars = self._templar._available_variables + for term in terms: display.debug("File lookup term: %s" % term) @@ -99,7 +102,7 @@ class LookupModule(LookupBase): # plus some added by ansible (e.g., template_{path,mtime}), # plus anything passed to the lookup with the template_vars= # argument. - vars = variables.copy() + vars = deepcopy(variables) vars.update(generate_ansible_template_vars(lookupfile)) vars.update(lookup_template_vars) self._templar.set_available_variables(vars) @@ -107,8 +110,12 @@ class LookupModule(LookupBase): # do the templating res = self._templar.template(template_data, preserve_trailing_newlines=True, convert_data=convert_data_p, escape_backslashes=False) + ret.append(res) else: raise AnsibleError("the template file %s could not be found for the lookup" % term) + # restore old variables + self._templar.set_available_variables(old_vars) + return ret