Skip to content
DevOps AI ToolKit
Newsletter
All prompts
AI for Ansible Difficulty: Intermediate ClaudeChatGPT

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.

Run this prompt with AI

Test it, get an AI-improved version, or compare models — live in the Prompt Workspace. No copy-paste.

Related prompts

More Ansible prompts & error guides

Browse every Ansible prompt and troubleshooting guide in one place.

Free download · 368-page PDF

Reading prompts? Get all 500 in one free PDF

500 battle-tested, copy-paste AI prompts engineered by a senior systems engineer — every one with fill-in placeholders and safety/back-out notes. Drop your email and it's yours.

  • 500 prompts: Linux · Kubernetes · Terraform · OpenStack · GitLab · Docker · Monitoring · Incident Response
  • Instant PDF download — yours free, forever
  • Plus one practical AI-workflow email a week (no spam)

Single opt-in · unsubscribe anytime · no spam.