diff --git a/changelog/55159.fixed b/changelog/55159.fixed new file mode 100644 index 00000000000..6ee1a783666 --- /dev/null +++ b/changelog/55159.fixed @@ -0,0 +1 @@ +Jinja renderer resolves wrong relative paths when importing subdirectories diff --git a/salt/utils/jinja.py b/salt/utils/jinja.py index 997d4b1697d..e1ac4657f97 100644 --- a/salt/utils/jinja.py +++ b/salt/utils/jinja.py @@ -155,7 +155,7 @@ def get_source(self, environment, template): 'Relative path "%s" cannot be resolved without an environment', template, ) - raise TemplateNotFound + raise TemplateNotFound(template) base_path = environment.globals["tpldir"] _template = os.path.normpath("/".join((base_path, _template))) if _template.split("/", 1)[0] == "..": diff --git a/salt/utils/templates.py b/salt/utils/templates.py index 1fda960b2e8..f369da5c9eb 100644 --- a/salt/utils/templates.py +++ b/salt/utils/templates.py @@ -492,9 +492,9 @@ def opt_jinja_env_helper(opts, optname): ) decoded_context[key] = salt.utils.data.decode(value) + jinja_env.globals.update(decoded_context) try: template = jinja_env.from_string(tmplstr) - template.globals.update(decoded_context) output = template.render(**decoded_context) except jinja2.exceptions.UndefinedError as exc: trace = traceback.extract_tb(sys.exc_info()[2]) diff --git a/tests/unit/utils/test_jinja.py b/tests/unit/utils/test_jinja.py index 807e901afa4..02195120971 100644 --- a/tests/unit/utils/test_jinja.py +++ b/tests/unit/utils/test_jinja.py @@ -612,6 +612,22 @@ def test_render_with_undefined_variable_unicode(self): dict(opts=self.local_opts, saltenv="test", salt=self.local_salt), ) + def test_relative_include(self): + template = "{% include './hello_import' %}" + expected = "Hey world !a b !" + filename = os.path.join(self.template_dir, "hello_import") + with salt.utils.files.fopen(filename) as fp_: + out = render_jinja_tmpl( + template, + dict( + opts=self.local_opts, + saltenv="test", + salt=self.local_salt, + tpldir=self.template_dir, + ), + ) + self.assertEqual(out, expected) + class TestJinjaDefaultOptions(TestCase): @classmethod