Skip to content

Commit

Permalink
Do not ignore SyntaxError from jinja2.Environment.from_string (ansibl…
Browse files Browse the repository at this point in the history
…e#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 ansible#82606

(cherry picked from commit 6d34eb8)
  • Loading branch information
mkrizek committed Jan 29, 2024
1 parent 5bef147 commit 05e413f
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
2 changes: 2 additions & 0 deletions changelogs/fragments/82606-template-python-syntax-error.yml
Original file line number Diff line number Diff line change
@@ -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)
2 changes: 1 addition & 1 deletion lib/ansible/template/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -973,7 +973,7 @@ def do_template(self, data, preserve_trailing_newlines=True, escape_backslashes=

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):
Expand Down
11 changes: 11 additions & 0 deletions test/integration/targets/templating/tasks/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"

0 comments on commit 05e413f

Please sign in to comment.