diff --git a/changelogs/fragments/75371-import_template_globals.yml b/changelogs/fragments/75371-import_template_globals.yml new file mode 100644 index 00000000000..e4cd774733f --- /dev/null +++ b/changelogs/fragments/75371-import_template_globals.yml @@ -0,0 +1,2 @@ +bugfixes: + - Jinja2 globals should be accessible even when importing a template without the context (https://github.com/ansible/ansible/issues/75371) diff --git a/lib/ansible/template/template.py b/lib/ansible/template/template.py index 5a555883a02..3e7738bf7d7 100644 --- a/lib/ansible/template/template.py +++ b/lib/ansible/template/template.py @@ -33,11 +33,13 @@ class AnsibleJ2Template(jinja2.environment.Template): ''' def new_context(self, vars=None, shared=False, locals=None): - if vars is not None: - if isinstance(vars, dict): - vars = vars.copy() - if locals is not None: - vars.update(locals) - else: - vars = vars.add_locals(locals) + if vars is None: + vars = dict(self.globals or ()) + + if isinstance(vars, dict): + vars = vars.copy() + if locals is not None: + vars.update(locals) + else: + vars = vars.add_locals(locals) return self.environment.context_class(self.environment, vars, self.name, self.blocks) diff --git a/test/integration/targets/template/tasks/main.yml b/test/integration/targets/template/tasks/main.yml index da803436860..c5744d0d012 100644 --- a/test/integration/targets/template/tasks/main.yml +++ b/test/integration/targets/template/tasks/main.yml @@ -715,5 +715,16 @@ assert: that: "\"'y' is undefined\" in error.msg" +- template: + src: template_import_macro_globals.j2 + dest: "{{ output_dir }}/template_import_macro_globals.templated" + +- command: "cat {{ output_dir }}/template_import_macro_globals.templated" + register: out + +- assert: + that: + - out.stdout == "bar=lookedup_bar" + # aliases file requires root for template tests so this should be safe - include: backup_test.yml diff --git a/test/integration/targets/template/templates/macro_using_globals.j2 b/test/integration/targets/template/templates/macro_using_globals.j2 new file mode 100644 index 00000000000..d8d0626d7e9 --- /dev/null +++ b/test/integration/targets/template/templates/macro_using_globals.j2 @@ -0,0 +1,3 @@ +{% macro foo(bar) -%} +{{ bar }}={{ lookup('lines', 'echo lookedup_bar') }} +{%- endmacro %} diff --git a/test/integration/targets/template/templates/template_import_macro_globals.j2 b/test/integration/targets/template/templates/template_import_macro_globals.j2 new file mode 100644 index 00000000000..9b9a9c68cc1 --- /dev/null +++ b/test/integration/targets/template/templates/template_import_macro_globals.j2 @@ -0,0 +1,2 @@ +{% from 'macro_using_globals.j2' import foo %} +{{ foo('bar') }}