From d2944d28130792f01cb2ec06955cdf687cd1ba61 Mon Sep 17 00:00:00 2001
From: Max Gautier <mg@max.gautier.name>
Date: Wed, 6 Dec 2023 03:05:24 +0100
Subject: [PATCH] Check jinja templates for syntax error (#10667)

Allow to fail early (pre-commit time) for jinja error, rather than
waiting until executing the playbook and the invalid template.

I could not find a simple jinja pre-commit hook in the wild.
---
 .gitlab-ci/lint.yml              | 8 ++++++++
 .pre-commit-config.yaml          | 9 +++++++++
 tests/scripts/check-templates.py | 9 +++++++++
 3 files changed, 26 insertions(+)
 create mode 100755 tests/scripts/check-templates.py

diff --git a/.gitlab-ci/lint.yml b/.gitlab-ci/lint.yml
index f8228672c..d8cebd227 100644
--- a/.gitlab-ci/lint.yml
+++ b/.gitlab-ci/lint.yml
@@ -27,6 +27,14 @@ ansible-lint:
     - ansible-lint -v
   except: ['triggers', 'master']
 
+jinja-syntax-check:
+  extends: .job
+  stage: unit-tests
+  tags: [light]
+  script:
+    - "find -name '*.j2' -exec tests/scripts/check-templates.py {} +"
+  except: ['triggers', 'master']
+
 syntax-check:
   extends: .job
   stage: unit-tests
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index b2d778634..c2380522a 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -69,3 +69,12 @@ repos:
         entry: tests/scripts/md-table/test.sh
         language: script
         pass_filenames: false
+
+      - id: jinja-syntax-check
+        name: jinja-syntax-check
+        entry: tests/scripts/check-templates.py
+        language: python
+        types:
+          - jinja
+        additional_dependencies:
+          - Jinja2
diff --git a/tests/scripts/check-templates.py b/tests/scripts/check-templates.py
new file mode 100755
index 000000000..1092a0d3e
--- /dev/null
+++ b/tests/scripts/check-templates.py
@@ -0,0 +1,9 @@
+#!/usr/bin/env python
+
+import sys
+from jinja2 import Environment
+
+env = Environment()
+for template in sys.argv[1:]:
+    with open(template) as t:
+        env.parse(t.read())
-- 
GitLab