Skip to content

Instantly share code, notes, and snippets.

@ndbroadbent
Last active November 2, 2023 16:36
Show Gist options
  • Save ndbroadbent/7c80201aca3b4025b943440605f48382 to your computer and use it in GitHub Desktop.
Save ndbroadbent/7c80201aca3b4025b943440605f48382 to your computer and use it in GitHub Desktop.
Script to compile and format *.yaml.jinja files in Home Assistant config directory (Including systemd service)
[Unit]
Description=Compile Jinja templates to YAML in Home Assistant config directory
After=network.target
StartLimitIntervalSec=0
[Service]
Type=simple
Restart=always
RestartSec=3
ExecStart=/opt/ha_compile_jinja.sh
[Install]
WantedBy=multi-user.target
#!/bin/bash
set -euo pipefail
HASS_CONFIG_DIR="/usr/share/hassio/homeassistant"
if ! type jinja > /dev/null 2>&1; then
echo "jinja-cli must be installed: pip install jinja-cli (https://pypi.org/project/jinja-cli/)"
sleep 1
exit 1
fi
if ! type prettier > /dev/null 2>&1; then
echo "Prettier must be installed: apt-get install nodejs npm && npm install -g prettier"
sleep 1
exit 1
fi
remove() {
OUTPUT_FILE="$1${2/.jinja}"
echo "$1$2 deleted, removing: $OUTPUT_FILE"
rm -f "$OUTPUT_FILE"
}
compile() {
echo "$1$2 changed, compiling to: $1${2/.jinja}"
ERROR_LOG_FILE="$1$2.errors.log"
OUTPUT_FILE="$1${2/.jinja}"
echo "# DO NOT EDIT: Generated from: $2 ($0)" > "$OUTPUT_FILE"
# Log any errors to an .errors.log file, delete if successful
if jinja "$1$2" >> "$OUTPUT_FILE" 2> "$ERROR_LOG_FILE"; then
(rm -f "$ERROR_LOG_FILE" || true)
echo "Formatting $OUTPUT_FILE with Prettier..."
prettier --write "$OUTPUT_FILE" --loglevel warn || true
else
(rm -f "$OUTPUT_FILE" || true)
echo "Error compiling $1$2!"
if [ -f "$ERROR_LOG_FILE" ]; then cat "$ERROR_LOG_FILE" >&2; fi
fi
}
echo "Compiling Jinja templates to YAML: $HASS_CONFIG_DIR/**/*.yaml.jinja"
inotifywait -q -m -r -e modify,delete,create,move "$HASS_CONFIG_DIR" | while read DIRECTORY EVENT FILE; do
if [[ "$FILE" != *.yaml.jinja ]]; then continue; fi
case $EVENT in
MODIFY*)
compile "$DIRECTORY" "$FILE";;
CREATE*)
compile "$DIRECTORY" "$FILE";;
MOVED_TO*)
compile "$DIRECTORY" "$FILE";;
DELETE*)
remove "$DIRECTORY" "$FILE";;
MOVED_FROM*)
remove "$DIRECTORY" "$FILE";;
esac
sleep 0.5
done
sleep 1
@tonyroberts
Copy link

I've wrapped this up as an addon here https://github.com/tonyroberts/hassio-jinja2config

Thanks @ndbroadbent, this was exactly what I was looking for to simplify some complex config!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment