CoursesAnsibleIntermediate

Templates & Jinja2

Generate config files from data.

Intermediate12 min · lesson 6 of 12

Most configuration is a file that differs slightly per host or environment, and the template module is how you generate it: you write a Jinja2 template with variables and logic, and Ansible renders it with the host’s variables and facts, then places the result. One template plus per-host variables replaces dozens of hand-maintained config files.

HOW THE TEMPLATE MODULE RENDERS A CONFIG
1Write Jinja2 template
.j2 with variables and logic
2Ansible renders it
substitutes host vars and facts
3Validate rendered file
validate: nginx -t — refuse if broken
4Place at dest
write to /etc/nginx/nginx.conf
5Notify handler
reload service only if it changed
Validate before it lands and reload via a handler so a bad config never takes the service down.
templates/nginx.conf.j2
worker_processes {{ nginx_worker_processes }};
http {
server {
listen {{ app_port }};
server_name {{ inventory_hostname }};
{% if enable_tls | default(false) %}
ssl_certificate {{ tls_cert_path }};
{% endif %}
}
}
task
- name: Render nginx config
ansible.builtin.template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
validate: nginx -t -c %s # test the file before accepting it
notify: reload nginx # trigger a handler only if it changed

Jinja2 in practice

Jinja2 gives you variable interpolation ({{ }}), conditionals ({% if %}), loops ({% for %}), and filters (| default, | upper, | to_json) — enough to express real config logic without turning templates into programs. The discipline is to keep logic minimal: templates should render data, not compute it. Compute values in variables and tasks, and let the template mostly substitute them.

Validate generated config before it lands
A templated config with a bad value can break a service on the next reload — an invalid nginx.conf takes the web tier down. Use the template module’s validate option (nginx -t, visudo -cf) so Ansible tests the rendered file and refuses to install a broken one, and pair templates with a handler so a service only reloads when the file actually changed.