Managing configuration files across dozens or hundreds of servers is where hand-edited files break down. One server ends up with a slightly different Nginx virtual host, another with an outdated database connection string, and debugging becomes a guessing game. Ansible Jinja2 templates solve this by letting you write a single template file with placeholders, then render a correct, customized configuration for every host from your inventory and variables. In this guide, you will learn how Ansible Jinja2 templates work, how to write them, and how to use them safely at scale.

Prerequisites
Before you start, make sure you have the following:
- Ansible installed on a control node (version 2.14 or later is recommended).
- At least one managed host reachable over SSH, or a local test host using
ansible_connection=local. - A working inventory file and basic familiarity with playbooks and variables.
- A text editor that handles Jinja2 syntax highlighting, which makes template errors much easier to spot.
If you are new to Ansible, start with our Ansible for Beginners guide to inventory, playbooks, and roles — it covers the inventory and role layout that templates build on.
Ansible Jinja2 Templates: How They Work
Ansible Jinja2 templates are plain text files with a .j2 extension that mix static content with Jinja2 expressions. When the template module runs, Ansible reads the template, replaces every expression with the value of the matching variable for that host, and writes the result to the destination path on the managed host. The template itself never leaves the control node — only the rendered output is copied over. That separation is the core idea behind Ansible Jinja2 templates: data lives in variables, structure lives in the template.
The three building blocks you will use most are:
{{ variable }}— prints the value of a variable.{% if ... %} ... {% endif %}— conditional blocks that include or skip content.{% for item in list %} ... {% endfor %}— loops that repeat a block for every item.
Jinja2 also provides filters, written with a pipe character, such as {{ port | default(80) }}, which keeps a playbook working even when a variable is not defined for every host.
Step 1: Render Your First Template
Create a role layout (or a simple directory) for the template. A role keeps templates organized under templates/ and variables under defaults/ or vars/:
roles/webserver/
templates/nginx-vhost.conf.j2
tasks/main.yml
defaults/main.yml
Write the template file templates/nginx-vhost.conf.j2:
server {
listen {{ nginx_port | default(80) }};
server_name {{ server_name }};
root {{ web_root }};
index index.html index.htm;
access_log /var/log/nginx/{{ server_name }}.access.log;
error_log /var/log/nginx/{{ server_name }}.error.log;
}
Define the variables in defaults/main.yml:
nginx_port: 80
server_name: example.com
web_root: /var/www/example.com
Then render the template with a task in tasks/main.yml:
- name: Deploy Nginx virtual host
ansible.builtin.template:
src: nginx-vhost.conf.j2
dest: /etc/nginx/sites-available/{{ server_name }}.conf
owner: root
group: root
mode: "0644"
notify: Reload Nginx
Run the playbook and check the rendered file on the managed host — it will contain the real values instead of the placeholders. The template module is idempotent: if the rendered output has not changed, the task reports no change and the handler does not fire. Once you see the rendered output, you understand why Ansible Jinja2 templates scale better than copying files by hand.
Step 2: Use Conditionals for Host-Specific Differences
Not every host needs the same configuration. Conditionals let one template serve web servers, staging servers, and production servers without forking into three files:
server {
listen {{ nginx_port }};
server_name {{ server_name }};
{% if enable_ssl | default(false) %}
listen 443 ssl;
ssl_certificate /etc/ssl/certs/{{ server_name }}.crt;
ssl_certificate_key /etc/ssl/private/{{ server_name }}.key;
{% endif %}
{% if environment == "production" %}
# Production-only hardening
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
{% endif %}
}
Set enable_ssl and environment per host or per group in your inventory, and each host renders exactly the block it needs. Keep conditionals simple — if a template grows more than two or three branches, split it into separate templates or move the logic into variables instead.
Step 3: Loop Over Lists and Dictionaries
Loops are where Ansible Jinja2 templates really pay off. Instead of writing ten nearly identical blocks, generate them from data. This example builds an Nginx upstream block from a list of application servers:
upstream app_backend {
{% for host in groups['appservers'] %}
server {{ hostvars[host]['ansible_host'] }}:8080;
{% endfor %}
}
server {
listen 80;
server_name {{ server_name }};
location / {
proxy_pass http://app_backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
This pattern works for firewall rules, cron entries, user accounts, DNS records, and any other configuration that repeats with small variations. When the inventory changes, the configuration regenerates itself on the next playbook run — no manual editing required. This data-driven approach is the reason Ansible Jinja2 templates are the default choice for generated configuration.
Step 4: Validate Before You Deploy
A template that renders successfully can still produce a broken configuration. The validate parameter of the template module runs a check command against the rendered file before it is moved into place, and aborts the task if validation fails:
- name: Deploy Nginx virtual host with validation
ansible.builtin.template:
src: nginx-vhost.conf.j2
dest: /etc/nginx/sites-available/{{ server_name }}.conf
validate: /usr/sbin/nginx -t -c %s
mode: "0644"
notify: Reload Nginx
Ansible replaces %s with the path of the temporary rendered file. Use the equivalent checker for other services — for example, sshd -t -f %s for SSH configuration or apachectl configtest for Apache. Validation turns a potentially site-breaking mistake into a harmless task failure.
Two more habits keep templates safe at scale. First, always back up the previous version with backup: true on the template task until you trust the output. Second, test rendering with ansible-playbook --check --diff before a real run: the diff shows exactly what will change on each host, line by line. Together, validation and previews make Ansible Jinja2 templates safe to run against production hosts.
Ansible Jinja2 Templates Troubleshooting
Undefined variable errors
Ansible stops with an error like 'server_name' is undefined when a template references a variable that no inventory, group, or role defines. Find where the variable should come from, or guard the reference with a default: {{ server_name | default('localhost') }}. For debugging, print all variables for a host with the debug module and var: hostvars[inventory_hostname].
Whitespace problems in rendered output
Jinja2 control lines ({% if %}, {% endfor %}) leave blank lines in the output. Most services tolerate blank lines, but for strict formats, add a minus sign to strip surrounding whitespace: {%- if ... -%}. Use this sparingly — overuse makes templates hard to read.
Template renders but the service fails to start
Check the rendered file on the host first, not the template. A wrong variable value (a port already in use, a missing directory) produces valid-looking output that the service rejects. Combine validate with --check --diff to catch these problems before they reach production.
Changes not applied on re-runs
If a task reports no change even though you edited the template, confirm you edited the .j2 file on the control node, not the rendered file on the host — manual edits to the rendered file are overwritten (or flagged as unexpected) on the next run. Also verify the task’s src path points at the file you changed.
Conclusion
Ansible Jinja2 templates replace fragile, hand-edited configuration files with a single source of truth that adapts to every host. Start with simple variable substitution, add conditionals for host differences, use loops for repeated blocks, and protect every deployment with validation and diff previews. Mastering Ansible Jinja2 templates pays off on every server you add afterward: adding a new server means adding one inventory entry, and the configuration takes care of itself. For the full filter and test reference, see the Ansible templating documentation and the Ansible template module documentation.