Lesson 11 / 26
Jinja2 Templates
Generate configuration files from templates using variables, defaults and loops.
One template, many files
The template module renders a Jinja2 file for each host and copies the result. Inside templates, {{ var }} prints a value, {{ var | default(80) }} supplies a fallback with a filter, and {% for %} loops. Use templates for configs that differ per host or environment, and keep static files in files/ for the copy module. A header comment such as "managed by Ansible" warns people not to edit the file by hand.
The template
http_port comes from the [web:vars] group in the inventory, users from the play's vars.
# managed by Ansible - do not edit
server_name={{ inventory_hostname }}
port={{ http_port | default(80) }}
{% for u in users %}
user={{ u }}
{% endfor %}The rendered file, run
This is the real out/web1.conf produced by the first run: the hostname, the port 8080 from the group variable, and one line per user.
# managed by Ansible - do not edit
server_name=web1
port=8080
user=asha
user=raviQuick check: What does `{{ http_port | default(80) }}` do?
- Raises an error if defined
- Always prints 80
- Deletes http_port
- Uses http_port if defined, otherwise 80
Answer
Uses http_port if defined, otherwise 80 — The default filter provides a fallback only when the variable is undefined.