From 6d34eb88d95c02013d781a29dfffaaf2901cd81f Mon Sep 17 00:00:00 2001 From: Martin Krizek Date: Mon, 29 Jan 2024 10:33:33 +0100 Subject: [PATCH] Do not ignore SyntaxError from jinja2.Environment.from_string (#82607) Jinja may generate an invalid Python source code from a template. Trying to compile such source code into a Python code object results in SyntaxError being thrown. An example of such a template is providing the same keyword argument into a lookup twice, resulting in: `SyntaxError: keyword argument repeated`. Since `jinja2.exceptions.TemplateSyntaxError` does not cover such a case, as it is not a Jinja parsing error, we need to catch SyntaxError explicitly ourselves. Fixes #82606 --- .../fragments/82606-template-python-syntax-error.yml | 2 ++ lib/ansible/template/__init__.py | 2 +- test/integration/targets/templating/tasks/main.yml | 11 +++++++++++ 3 files changed, 14 insertions(+), 1 deletion(-) create mode 100644 changelogs/fragments/82606-template-python-syntax-error.yml diff --git a/changelogs/fragments/82606-template-python-syntax-error.yml b/changelogs/fragments/82606-template-python-syntax-error.yml new file mode 100644 index 00000000000..4bb13714193 --- /dev/null +++ b/changelogs/fragments/82606-template-python-syntax-error.yml @@ -0,0 +1,2 @@ +bugfixes: + - templating - ensure syntax errors originating from a template being compiled into Python code object result in a failure (https://github.com/ansible/ansible/issues/82606) diff --git a/lib/ansible/template/__init__.py b/lib/ansible/template/__init__.py index c00099c29af..efdaa0aec74 100644 --- a/lib/ansible/template/__init__.py +++ b/lib/ansible/template/__init__.py @@ -945,7 +945,7 @@ class Templar: try: t = myenv.from_string(data) - except TemplateSyntaxError as e: + except (TemplateSyntaxError, SyntaxError) as e: raise AnsibleError("template error while templating string: %s. String: %s" % (to_native(e), to_native(data)), orig_exc=e) except Exception as e: if 'recursion' in to_native(e): diff --git a/test/integration/targets/templating/tasks/main.yml b/test/integration/targets/templating/tasks/main.yml index 312e171de37..edbf012e380 100644 --- a/test/integration/targets/templating/tasks/main.yml +++ b/test/integration/targets/templating/tasks/main.yml @@ -33,3 +33,14 @@ - result is failed - >- "TemplateSyntaxError: Could not load \"asdf \": 'invalid plugin name: ansible.builtin.asdf '" in result.msg + +- name: Make sure syntax errors originating from a template being compiled into Python code object result in a failure + debug: + msg: "{{ lookup('vars', 'v1', default='', default='') }}" + ignore_errors: true + register: r + +- assert: + that: + - r is failed + - "'keyword argument repeated' in r.msg"