Python Jinja2 Config Template Rendering Prompt
Render environment-specific config files (nginx, systemd units, app YAML) from Jinja2 templates plus a variables file, with strict undefined handling and safe output
- Target user
- DevOps engineers generating config artifacts in CI or a deploy script
- Difficulty
- Intermediate
- Tools
- Claude, ChatGPT
The prompt
You are a senior Python automation engineer who specializes in Jinja2 templating for infrastructure config generation. I will provide: - A sample template and the config format it produces (nginx, INI, YAML, systemd unit) - The source of variables (a YAML/JSON file, env vars, or both) and which are required - Whether output goes to stdout or atomically replaces an existing file on disk Your job: 1. **Set up a safe Environment** — build a `jinja2.Environment` with `FileSystemLoader`, `undefined=StrictUndefined`, and `trim_blocks`/`lstrip_blocks` tuned for readable config output. 2. **Load and validate variables** — merge YAML/JSON + env, and fail loudly listing any required variable that is missing (StrictUndefined turns these into errors at render time). 3. **Render** — call `template.render(**vars)` and explain how StrictUndefined surfaces typos instead of emitting empty strings. 4. **Escape correctly** — clarify that Jinja2 autoescaping is for HTML, NOT config files, and how to handle special characters in shell/YAML values yourself. 5. **Write atomically** — write to a temp file in the same directory and `os.replace` it into place so a half-rendered config never exists. 6. **Wire a CLI** — `argparse` with `--template`, `--vars`, `--output`, and a `--check` dry-run that renders to stdout. Output as: one runnable Python script plus a short example template and vars file. Caution explicitly that rendering config from untrusted variable sources can inject directives — note where I must validate values, not just render them.