Infrastructure as code · Intermediate · 22 min
Template config files with Ansible, Jinja2 and handlers
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · ansible-core 2.22.0 · Nginx from the Ubuntu archive
You will generate an Nginx server block from a Jinja2 template with ansible-core 2.22, have Ansible test each file before installing it, reload Nginx once and only when the config changed, and review every change with a diff before it lands.
On this page
Copying a hand-written config file to a server works until you have three servers that need almost the same file. Then you keep three copies, they drift, and a typo in one of them takes a site down at reload time. A template fixes the first problem: one file with placeholders, filled in per server from variables. Ansible's template module, with a validate command and a handler, fixes the second: the new file is tested before it replaces the old one, and Nginx reloads only when something really changed.
In this tutorial you build that for a small site called shop. The server block uses Jinja2 variables, a loop, a conditional and filters. Each file is checked before it is installed. Two tasks notify the same reload handler and it still runs once. You flush handlers halfway through the play so a smoke test can hit the new config, break a value on purpose to watch validation stop it, and review a change with --check --diff before applying it. Every file Ansible writes carries a header saying so.
Step 1 · Install ansible-core and set up the project
Everything in this tutorial uses modules and filters from ansible.builtin, so ansible-core on its own is enough. Install it from PyPI with pipx, pinned so your output matches this page. ansible-core 2.22 needs Python 3.13 or newer, which Ubuntu 26.04 has:
sudo apt update
sudo apt install -y pipx openssh-client
pipx install ansible-core==2.22.0
export PATH="$HOME/.local/bin:$PATH"
ansible --version | head -n 1If you already installed the full ansible package with pipx for another tutorial, skip the pipx install line: Ansible 15.0.0 already contains ansible-core 2.22. Add the PATH line to ~/.bashrc (or run pipx ensurepath) so new terminals find the commands. This install gets no updates from apt; upgrade it with pipx upgrade ansible-core when you choose to.
Make a project folder with a config file that points at the inventory, so you can leave out -i on every command:
mkdir -p ~/ansible-templates-demo/templates ~/ansible-templates-demo/vars
cd ~/ansible-templates-demo
cat > ansible.cfg <<'CFG'
[defaults]
inventory = inventory.ini
CFGNow the inventory. Replace the address and user with your server's (203.0.113.10 is a documentation address and will not connect):
cat > inventory.ini <<'INI'
[web]
web1 ansible_host=203.0.113.10
[web:vars]
ansible_user=deploy
ansible_python_interpreter=/usr/bin/python3
INICheck it worked
ansible --version | head -n 1
ansible web -m pingThe first line starts with ansible [core 2.22.0]. The ping prints web1 | SUCCESS and "ping": "pong". If it says UNREACHABLE!, fix plain ssh deploy@<your server> first; see /tutorials/log-in-to-a-server-with-ssh-keys.
Step 2 · Write the variables and the server block template
Keep the values that differ between sites in a variables file, and keep the templates free of literal names and sizes. Then a second site is a second variables file, not a copy of the template:
cat > vars/shop.yml <<'YAML'
# Values for the shop site. Change these, not the templates.
managed_by: "Managed by Ansible from ansible-templates-demo. Local edits are overwritten on the next run."
site_name: shop
server_names:
- shop.example.com
- www.shop.example.com
site_root: /var/www/shop
max_body_size: 10m
enable_gzip: true
gzip_types:
- text/css
- application/javascript
- application/json
locations:
- path: /static/
expires: 7d
- path: /downloads/
autoindex: true
site_info:
_managed: "{{ managed_by }}"
site: "{{ site_name }}"
server_names: "{{ server_names }}"
locations: "{{ locations | map(attribute='path') | list }}"
YAMLmanaged_by is the header text every file will carry. It has no date or time in it on purpose: a header that changes on every run would make every run report a change and reload Nginx for nothing. Older playbooks use {{ ansible_managed }}, whose text comes from ansible.cfg; that setting is deprecated in ansible-core 2.22 and due to be removed in 2.23, so a variable of your own is the safer habit.
Now the template. Jinja2 has two kinds of markup: {{ ... }} prints a value, and {% ... %} is logic (if, for) that prints nothing itself:
cat > templates/shop.conf.j2 <<'J2'
{{ managed_by | comment }}
server {
listen {{ listen_port | default(80) }};
server_name {{ server_names | join(' ') }};
root {{ site_root }};
index index.html;
client_max_body_size {{ max_body_size }};
{% if enable_gzip %}
gzip on;
gzip_types {{ gzip_types | join(' ') }};
{% endif %}
location / {
try_files $uri $uri/ =404;
}
{% for loc in locations %}
location {{ loc.path }} {
expires {{ loc.expires | default('1h') }};
{% if loc.autoindex | default(false) %}
autoindex on;
{% endif %}
}
{% endfor %}
}
J2What each piece does:
commentturns the header text into a block of#lines, which is Nginx's comment syntax.default(80)supplies a value when a variable is not set at all.listen_portis not in the variables file, so the site listens on 80, and a host that needs another port setslisten_portwithout touching the template. The same filter gives/downloads/anexpiresof1hand makesautoindexoptional per location.join(' ')turns the list of names into the single space-separated line Nginx wants.{% if enable_gzip %}keeps or drops the whole gzip block. Compressed CSS and JavaScript, plusexpiresheaders that let browsers keep static files, cut the data each visit costs, which matters to readers on prepaid mobile data and low-end Android phones.{% for loc in locations %}writes onelocationblock per list item.
Ansible renders templates with trim_blocks on, so a line holding only a {% ... %} tag leaves no blank line behind. Nginx's own $uri is safe in the template because Jinja2 only reacts to {{, {% and {#.
Check it worked
Render the template on your own machine, without touching the server. ansible localhost runs against the control machine, and -e @vars/shop.yml loads the variables file:
ansible localhost -m ansible.builtin.template -a "src=templates/shop.conf.j2 dest=$PWD/shop-preview.conf" -e @vars/shop.yml
cat shop-preview.confThe file starts with three # lines around the header text. You see listen 80;, server_name shop.example.com www.shop.example.com;, the gzip block, and three location blocks, with autoindex on; only under /downloads/, which also got expires 1h;.
Step 3 · Write a checker and the other templates
The template module's validate option runs a command against the rendered file before moving it into place. %s stands for a temporary copy of the new file; if the command fails, the task fails and the live file is left alone. For a complete nginx.conf, validate: nginx -t -c %s does the job directly. A server block on its own is not a complete config: nginx -t would reject it because a server block is only allowed inside http. The command is also run without a shell, so pipes and redirects in it do not work.
The fix is a small script that wraps the block in a minimal config and tests that. Ansible installs it too, from a template, so it carries the header:
cat > templates/nginx-check-site.j2 <<'J2'
#!/bin/sh
{{ managed_by | comment }}
# Test one Nginx server block by wrapping it in a minimal nginx.conf.
# Usage: nginx-check-site /path/to/site.conf
set -eu
wrapper=$(mktemp /tmp/nginx-check-XXXXXX.conf)
trap 'rm -f "$wrapper"' EXIT
cat > "$wrapper" <<EOF
events {}
http {
include /etc/nginx/mime.types;
include $1;
}
EOF
nginx -t -q -c "$wrapper"
J2nginx -t tests a config without loading it, -c names the file to test, and -q hides the success messages so only errors print. The wrapper tests the syntax and directives of this one block; a clash with another site on the server (two blocks claiming the same name, for example) only shows when the full config is tested, which you do in the check below.
Two more files make up the site: a home page, and a JSON file describing the site. JSON has no comments, so the header goes in as a _managed key instead:
cat > templates/index.html.j2 <<'J2'
<!-- {{ managed_by }} -->
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>{{ site_name | title }}</title></head>
<body>
<h1>{{ site_name | title }}</h1>
<p>Served as {{ server_names | first }} by {{ inventory_hostname }}.</p>
</body>
</html>
J2
cat > templates/site-info.json.j2 <<'J2'
{{ site_info | to_nice_json }}
J2to_nice_json turns the site_info dictionary into indented JSON with sorted keys, so the file comes out the same on every run. Never build JSON by pasting strings together in a template: one quote in a value breaks it, and the filter handles the escaping.
Check it worked
ls templatesYou see four files: index.html.j2, nginx-check-site.j2, shop.conf.j2 and site-info.json.j2.
Step 4 · Write the playbook with validation and a handler
The playbook installs Nginx, puts each file in place with a check, and uses one handler for the reload:
cat > site.yml <<'YAML'
- name: Serve the shop site from templates
hosts: web
become: true
vars_files:
- vars/shop.yml
tasks:
- name: Install Nginx
ansible.builtin.apt:
name: nginx
state: present
update_cache: true
cache_valid_time: 3600
- name: Make sure Nginx is running
ansible.builtin.service:
name: nginx
state: started
enabled: true
- name: Install the server block checker
ansible.builtin.template:
src: templates/nginx-check-site.j2
dest: /usr/local/sbin/nginx-check-site
owner: root
group: root
mode: "0755"
validate: sh -n %s
- name: Write the server block
ansible.builtin.template:
src: templates/shop.conf.j2
dest: /etc/nginx/sites-available/shop.conf
owner: root
group: root
mode: "0644"
validate: /usr/local/sbin/nginx-check-site %s
notify: Reload Nginx
- name: Enable the site
ansible.builtin.file:
src: /etc/nginx/sites-available/shop.conf
dest: /etc/nginx/sites-enabled/shop.conf
state: link
notify: Reload Nginx
- name: Create the site folders
ansible.builtin.file:
path: "{{ site_root }}{{ item }}"
state: directory
mode: "0755"
loop: "{{ [''] + (locations | map(attribute='path') | list) }}"
- name: Write the home page
ansible.builtin.template:
src: templates/index.html.j2
dest: "{{ site_root }}/index.html"
mode: "0644"
- name: Write the site info file
ansible.builtin.template:
src: templates/site-info.json.j2
dest: "{{ site_root }}/site-info.json"
mode: "0644"
validate: python3 -m json.tool %s
- name: Reload Nginx now if its config changed
ansible.builtin.meta: flush_handlers
- name: Fetch the site info through Nginx
ansible.builtin.uri:
url: http://127.0.0.1/site-info.json
headers:
Host: "{{ server_names | first }}"
return_content: true
register: site_check
when: not ansible_check_mode
- name: Check that Nginx serves the shop site
ansible.builtin.assert:
that:
- site_check.json.site == site_name
success_msg: "{{ server_names | first }} is live"
when: not ansible_check_mode
handlers:
- name: Reload Nginx
ansible.builtin.service:
name: nginx
state: reloaded
YAMLHow the pieces fit:
- Every file gets a
validatecommand that suits it:sh -nreads the script without running it, the checker tests the server block, andpython3 -m json.toolrefuses invalid JSON. - The server block and the link both
notify: Reload Nginx. A handler runs once however many tasks notify it, and only if at least one of them reportedchanged. - Handlers normally wait for the end of the play.
meta: flush_handlersruns any pending ones at that point instead, so the smoke test after it talks to the reloaded Nginx, not the old config. - The
uritask asks Nginx on the server forsite-info.jsonwith the site'sHostheader, andassertfails the run if the answer is not the shop site. Both skip themselves in check mode, which you use later, because nothing is reloaded in a check. - The folder loop creates
/var/www/shop(the empty string) plus one folder per location.
Run it and keep a copy of the output:
ansible-playbook site.yml | tee first-run.logIf your user needs a password for sudo, add --ask-become-pass. The play lists each task as changed or ok. Near the end you see RUNNING HANDLER [Reload Nginx] straight after the flush, before the fetch task, and then the assertion prints shop.example.com is live. The recap ends with failed=0; the changed count depends on what the server had before (something like changed=7 on a fresh server).
Check it worked
grep -c 'RUNNING HANDLER \[Reload Nginx\]' first-run.log
ansible web -b -a "nginx -t"
ansible web -a "curl -s -H 'Host: shop.example.com' http://127.0.0.1/site-info.json"The first command prints 1: two tasks notified the handler and it ran once. nginx -t on the full config says the syntax is ok and the test is successful. The curl, run on the server itself, returns the JSON with "site": "shop" and both server names.
Step 5 · Run it again, then feed it a bad value
Run the same playbook a second time:
ansible-playbook site.yml | tee second-run.log
grep 'changed=' second-run.logThe recap line now shows changed=0, and there is no RUNNING HANDLER line: no template produced different content, so nothing notified the handler and Nginx was not reloaded. That is what lets you run the playbook from a schedule without reloading every server every time.
Now see validation do its job. Extra variables passed with -e outrank the variables file, so this run tries to write client_max_body_size ten-megabytes;, which Nginx does not accept:
ansible-playbook site.yml -e max_body_size=ten-megabytes | tee bad-run.log || echo "The run stopped, as expected"The task Write the server block fails with something like "msg": "failed to validate", and its stderr holds the Nginx error naming client_max_body_size and an invalid value. The play stops for that host, so no handler runs, and the recap shows failed=1.
Check it worked
ansible web -a "grep client_max_body_size /etc/nginx/sites-available/shop.conf"The live file still says client_max_body_size 10m;. Without validate, the broken file would have been installed and the reload would have failed, leaving the next restart of Nginx to fail too.
Step 6 · Review a change with --check and --diff
Say the shop needs larger uploads and a second domain. Write the new variables file (the only changes are max_body_size and a third name):
cat > vars/shop.yml <<'YAML'
# Values for the shop site. Change these, not the templates.
managed_by: "Managed by Ansible from ansible-templates-demo. Local edits are overwritten on the next run."
site_name: shop
server_names:
- shop.example.com
- www.shop.example.com
- shop.example.org
site_root: /var/www/shop
max_body_size: 25m
enable_gzip: true
gzip_types:
- text/css
- application/javascript
- application/json
locations:
- path: /static/
expires: 7d
- path: /downloads/
autoindex: true
site_info:
_managed: "{{ managed_by }}"
site: "{{ site_name }}"
server_names: "{{ server_names }}"
locations: "{{ locations | map(attribute='path') | list }}"
YAMLPreview the effect. --check reports what would change without changing it, and --diff prints the file differences:
ansible-playbook site.yml --check --diff | tee check-run.logUnder Write the server block you see a diff with lines like - client_max_body_size 10m; and + client_max_body_size 25m;, and the server_name line with shop.example.org added. Write the site info file shows the new name added to the JSON list. The handler is listed but, in check mode, only reports what it would do. Read the diff the way you would read a pull request: it is the exact text that will land on the server.
Happy with it? Apply it, still with --diff so the log records what changed:
ansible-playbook site.yml --diff | tee apply-run.logCheck it worked
grep -c 'RUNNING HANDLER \[Reload Nginx\]' apply-run.log
ansible web -a "curl -s -H 'Host: shop.example.org' http://127.0.0.1/site-info.json"The count is 1: only the server block changed among the notifying tasks, and Nginx reloaded once. The new domain answers with the shop's JSON, with three names in server_names.
Step 7 · Check the managed header, then clean up
The header is a promise: anyone who opens one of these files on the server learns that the copy in Git is the real one. Every file Ansible wrote should carry it:
ansible web -a "grep -l 'Managed by Ansible' /etc/nginx/sites-available/shop.conf /usr/local/sbin/nginx-check-site /var/www/shop/index.html /var/www/shop/site-info.json"Ansible prints all four paths. A missing header makes grep exit non-zero and the host shows FAILED with the files that did match.
Now see the promise kept. Make a quick fix by hand on the server, the kind that gets forgotten, then run the playbook with --diff:
ansible web -b -m ansible.builtin.shell -a "echo '# quick fix by hand' >> /etc/nginx/sites-available/shop.conf"
ansible-playbook site.yml --diff | tee drift-run.logCheck it worked
grep -F -- '-# quick fix by hand' drift-run.logThe diff shows the hand-made line being removed, and the handler reloads Nginx. If a change matters, it belongs in the variables or the template, where the next run keeps it.
When you are finished, remove what this tutorial put on the server. This playbook deletes the site's config, its folder under /var/www/shop and the checker script, then reloads Nginx:
cat > cleanup.yml <<'YAML'
- name: Remove the shop site
hosts: web
become: true
tasks:
- name: Remove the site files and the checker
ansible.builtin.file:
path: "{{ item }}"
state: absent
loop:
- /etc/nginx/sites-enabled/shop.conf
- /etc/nginx/sites-available/shop.conf
- /var/www/shop
- /usr/local/sbin/nginx-check-site
notify: Reload Nginx
handlers:
- name: Reload Nginx
ansible.builtin.service:
name: nginx
state: reloaded
YAML
ansible-playbook cleanup.ymlThe next command uninstalls Nginx and its config. Run it only if you installed Nginx for this tutorial and nothing else on the server uses it:
ansible web -b -m ansible.builtin.apt -a "name=nginx state=absent purge=true autoremove=true"Then remove the project folder and Ansible from your machine:
cd ~
rm -rf ~/ansible-templates-demo
pipx uninstall ansible-coreNext steps
- Move
vars/shop.ymlinto a proper inventory layout, with values per group and per host:/tutorials/organise-ansible-variables-with-group-vars-and-host-vars. - Package the templates, the checker and the handler as a reusable role:
/tutorials/organise-ansible-work-into-roles. - Keep passwords and keys that templates need out of plain text:
/tutorials/encrypt-secrets-with-ansible-vault. - Go back over the inventory and playbook basics:
/tutorials/configure-a-server-with-an-ansible-playbook.
Related tutorials
- How to Configure a Server with an Ansible PlaybookYou will install Ansible 14 on your own computer, describe a web server's setup in a playbook, apply it over SSH, run it a second time to see that nothing changes, and preview a change with check mode before applying it.
- Organise Ansible variables with group_vars, host_vars and precedenceYou will lay out a staging and production Ansible inventory with values split across group_vars and host_vars, prove which of four competing settings wins, and leave with a rule for where each kind of value belongs.
- Organise Ansible work into reusable rolesYou will split a one-file Ansible playbook into a base role and a web role, pull in a pinned community role from requirements.yml, and finish with a site.yml that runs cleanly a second time with changed=0.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials