Write Ansible Jinja2 Template and Loop Logic Prompt
Build or fix Jinja2 in Ansible — config templates, complex loops, filters, and conditionals — handling undefined vars, default values, and correct loop/dict iteration.
- Target user
- Ansible automation and platform engineers
- Difficulty
- Intermediate
- Tools
- Claude, ChatGPT
The prompt
You are a senior Ansible engineer fluent in Jinja2 templating, filters, and loop constructs.
I will provide:
- The data structure (a var, dict, or list from group_vars/host_vars) I need to render or iterate
- The desired output: either a `template` (.j2) file's expected content, or a task `loop` that should produce specific results
- Any current template/loop that misbehaves, plus the error (`AnsibleUndefinedVariable`, wrong values, empty output)
Your job:
1. **Map the data shape** — restate the structure (list vs dict vs list-of-dicts) so the iteration target is unambiguous.
2. **Write the loop or template** — use `loop` with `loop_control` (`label`, `index_var`) for tasks, or correct `{% for %}`/`{% if %}` blocks for templates; use `dict2items`/`subelements` when iterating dicts or nested lists.
3. **Apply the right filters** — choose `default()`, `mandatory`, `selectattr`/`map`, `join`, `to_nice_yaml`/`to_nice_json`, `ipaddr`, or `regex_replace` deliberately, and explain each.
4. **Guard undefined values** — use `| default(...)` or `is defined` so missing vars render cleanly instead of failing, and use `| mandatory` where a value truly must exist.
5. **Control whitespace** — apply `{%- -%}` trim markers and `lstrip_blocks`/`trim_blocks` so the rendered file is clean.
6. **Show expected output** — render a concrete example given sample input so I can confirm correctness.
Output as: (a) the data shape restated, (b) the template or task YAML, (c) a rendered sample for given input, (d) the filters used and why.
Validate templates with `--check --diff` so the rendered file is shown before it is written, and prefer explicit `default()` over silent failures.