Globals should be accessible when importing a template without the context (#75384)

Fixes #75371
pull/75413/head
Martin Krizek 3 years ago committed by GitHub
parent 1b95b1e7a4
commit 5a38076568
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -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)

@ -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)

@ -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
- import_tasks: backup_test.yml

@ -0,0 +1,3 @@
{% macro foo(bar) -%}
{{ bar }}={{ lookup('lines', 'echo lookedup_bar') }}
{%- endmacro %}

@ -0,0 +1,2 @@
{% from 'macro_using_globals.j2' import foo %}
{{ foo('bar') }}
Loading…
Cancel
Save