Jinja2 Templates
When a whole config file depends on variables, write it as a Jinja2 template (templates/*.j2) and render it with the template module. The template module renders on the control node, then copies the result with the same idempotency, mode, backup and validate options as copy.
Jinja2 in one table
| Syntax | Meaning |
|---|---|
{{ expr }} |
print a value |
{% if … %}…{% elif … %}…{% else %}…{% endif %} |
condition |
{% for x in list %}…{% endfor %} |
loop; loop.index, loop.first, loop.last inside |
{{ value | filter }} |
transform: default, upper, join, to_nice_yaml, … (Filters) |
{# comment #} |
not in the output |
{%- … -%} |
strip whitespace before/after the tag |
A load balancer config from the inventory
The classic example: HAProxy or Nginx needs the list of back-end servers, which is exactly the inventory group web.
mkdir -p templates out
printf '[defaults]\ninterpreter_python = auto_silent\n' > ansible.cfg
cat > hosts.ini <<'INI'
[web]
web1 ansible_connection=local private_ip=10.0.1.10
web2 ansible_connection=local private_ip=10.0.1.11
web3 ansible_connection=local private_ip=10.0.1.12 web_weight=50
[lb]
lb1 ansible_connection=local
INI
cat > templates/upstream.conf.j2 <<'J2'
# {{ ansible_managed }}
upstream {{ app_name }} {
{% for host in groups['web'] | sort %}
server {{ hostvars[host].private_ip }}:{{ app_port }}{% if hostvars[host].web_weight is defined %} weight={{ hostvars[host].web_weight }}{% endif %};
{% endfor %}
{% if keepalive | default(true) %}
keepalive 32;
{% endif %}
}
J2
cat > lb.yml <<'YML'
- name: Load balancer
hosts: lb
gather_facts: false
vars:
app_name: linkly
app_port: 8080
tasks:
- name: Upstream config
ansible.builtin.template:
src: upstream.conf.j2
dest: out/upstream.conf
mode: "0644"
YML
ansible-playbook -i hosts.ini lb.yml | grep -E '^(ok|changed)'
cat out/upstream.confchanged: [lb1]
# Ansible managed
upstream linkly {
server 10.0.1.10:8080;
server 10.0.1.11:8080;
server 10.0.1.12:8080 weight=50;
keepalive 32;
}
Points to notice:
templatelooks forsrcintemplates/next to the playbook (or in the role'stemplates/).{{ ansible_managed }}prints a "do not edit" banner; put it at the top of every generated file, in the file's own comment syntax.trim_blocksis on in Ansible: the newline after a{% … %}tag is removed, which is why theforlines left no blank lines. Leading spaces of tag lines stay unless you use{%-orlstrip_blocks.default(true)makeskeepaliveoptional.
Diff and validate
With --diff, template changes show as a unified diff, as with copy. On a real server always add validate: for configs that have a checker, so a typo never reaches the service:
- name: Nginx site
ansible.builtin.template:
src: site.conf.j2
dest: /etc/nginx/sites-available/linkly.conf
validate: nginx -t -c /etc/nginx/nginx.conf # whole-config check
notify: Reload nginx
- name: sudoers drop-in
ansible.builtin.template:
src: sudoers.j2
dest: /etc/sudoers.d/deploy
mode: "0440"
validate: visudo -cf %s # %s = the rendered temp fileUndefined variables fail loudly
A template that uses an undefined variable fails the task instead of writing an empty value, which is what you want:
mkdir templates
printf 'port={{ app_port }}\n' > templates/app.conf.j2
cat > t.yml <<'YML'
- name: Undefined variable
hosts: localhost
gather_facts: false
tasks:
- name: Render
ansible.builtin.template:
src: app.conf.j2
dest: app.conf
mode: "0644"
YML
ansible-playbook t.yml 2>&1 | grep -E '^(fatal|\[ERROR\])' | cut -c1-110[ERROR]: Task failed: 'app_port' is undefined
fatal: [localhost]: FAILED! => {"changed": false, "msg": "Task failed: 'app_port' is undefined"}
Give optional values a default in the template, and required ones a role default or an assert.
Test yourself
Where does the template module render the Jinja2?
- On the managed host
- On the control node, then copies the result
- In the browser
- In a container
Which expression lists all hosts of the inventory group web in a template?
{{ web.hosts }}{{ groups['web'] }}{{ hostvars.web }}{{ group_names }}
What does validate: visudo -cf %s do?
- Checks the rendered temp file before it replaces the real one
- Runs visudo after the change
- Validates YAML
- Sets the file mode