Ansible Templates with Jinja2
A template is a configuration file with the machine-specific parts left as expressions, and it is the single most useful thing Ansible does. This builds one that uses every feature you actually need - variables, facts, arithmetic, a for loop, an if - deploys it with validation and a backup, and finishes with the filters worth memorising.
Templates, Files and Vault Guide 18 of 45 Intermediate
- OSUbuntu 26.04 LTS
- ansible-core2.20.1
- Python3.14.4
- TimeAbout 17 min
template renders on the control node and copies the result, so the managed node never needs Jinja2 or the variables. It is copy with a render step, and it takes the same owner, group, mode, backup and validate parameters.
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| ANS-CTL01 | 192.168.0.36 | Ubuntu 26.04 LTS | Ansible Control Node | 2 Core | 3 GB | 50 GB |
| ANS-A01 | 192.168.0.37 | Ubuntu 26.04 LTS | Managed Node (group: web) | 2 Core | 3 GB | 50 GB |
This guide includes
Use this when a configuration file has to differ per host. This matters because a template is that file with the machine-specific parts left as expressions - and rendering it twice changes nothing, which is what makes it safe to re-run.
- writing a template as a config file with holes left in it
- rendering it with the
templatemodule - running it again and getting
changed=0 - changing one variable, and diffing exactly what that did
- using the Jinja filters that earn their keep
Before you start
- A control node configured as shown in the first step.
- The session writes
~/pb/templates/app.conf.j2, deploys it to/etc/app.confon thewebhost, and removes it at the end.
-
The configuration this guide assumes
-
A template is a config file with holes in it
-
Render it
-
Running it again changes nothing
-
Change one variable and diff it
-
The filters that earn their keep