template module - Report syntax error line number (#86101)

Report the line number for Jinja syntax errors in template files.
This commit is contained in:
Matt Clay
2025-11-05 17:11:17 -08:00
committed by GitHub
parent 8ac5c8580b
commit a4ae978122
6 changed files with 37 additions and 0 deletions

View File

@@ -0,0 +1,2 @@
bugfixes:
- template module - Report the line number for Jinja syntax errors in template files.

View File

@@ -496,6 +496,14 @@ def create_template_error(ex: Exception, variable: t.Any, is_expression: bool) -
if isinstance(ex, RecursionError):
msg = f"Recursive loop detected in {kind}."
elif isinstance(ex, TemplateSyntaxError):
if (origin := Origin.get_tag(variable)) and origin.line_num is None and ex.lineno > 0:
# When there is an origin without a line number, use the line number provided by the Jinja syntax error.
# This should only occur on templates which represent the entire contents of a file.
# Templates loaded from within a file, such as YAML, will use the existing origin.
# It's not possible to combine origins here, due to potential layout differences between the original content and the parsed output.
# This can happen, for example, with YAML multi-line strings.
variable = origin.replace(line_num=ex.lineno, col_num=None).tag(variable)
msg = f"Syntax error in {kind}."
if is_expression and is_possibly_template(variable):

View File

@@ -0,0 +1,2 @@
context/controller
shippable/posix/group4

View File

@@ -0,0 +1,13 @@
#!/usr/bin/env bash
set -eux
ansible-playbook template-file.yml "${@}" | tee template-file.out
echo "Verifying contents of error reports ..."
# verify the template-file error report is correct
grep 'template-file.j2:5' template-file.out
grep '5 {% sorry' template-file.out
echo "PASS"

View File

@@ -0,0 +1,5 @@
line 1
line 2
line 3
line 4
{% sorry

View File

@@ -0,0 +1,7 @@
- hosts: localhost
gather_facts: no
tasks:
- template:
src: template-file.j2
dest: template-file.txt
ignore_errors: yes