Templates & Jinja2
Generate config files from data.
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.
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 %}}}
- name: Render nginx configansible.builtin.template:src: nginx.conf.j2dest: /etc/nginx/nginx.confvalidate: nginx -t -c %s # test the file before accepting itnotify: 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.