Jinja2 {% for %} and {% if %} are used in templates. What do you use in a playbook instead?
In playbooks, repetition and conditions are task keywords: loop instead of {% for %} and when instead of {% if %}; Jinja2 control structures belong in template files.
| Need | In a template | In a playbook |
|---|---|---|
| Repeat | {% for x in list %} ... {% endfor %} |
loop: "{{ list }}" on the task |
| Condition | {% if cond %} ... {% endif %} |
when: cond on the task |
| Insert a value | {{ expr }} |
"{{ expr }}" in a value |
The reason is what each file is. A template's output is text, so text-generating control flow fits. A playbook is YAML that describes tasks, and Ansible needs to see each task, its iterations and its skip decisions, to report them, notify handlers and handle errors. A {% for %} hidden inside a string value would produce text that Ansible can't treat as separate tasks.
So in playbooks Jinja2 appears as expressions ({{ }}, filters, tests), while the structure comes from loop, when, block and the like.
Go deeper:
Templating (Jinja2) (official docs) — where Jinja2 is evaluated in playbooks.