Please enable JavaScript.
Coggle requires JavaScript to display documents.
Phase 10 – Templates (Jinja2) - Coggle Diagram
Phase 10 – Templates (Jinja2)
What are Templates
Definition
A template is a text file containing variables, logic, and expressions that Ansible converts into a final configuration file before copying it to the managed host.
Purpose
Create dynamic configuration files.
Avoid maintaining separate configuration files for every server.
Use variables to customize configurations automatically.
Standardize enterprise deployments.
Common Uses
Apache configuration
Nginx configuration
SSH configuration
DNS configuration
Database configuration
Application configuration
System reports
Configuration backups
HTML pages
JSON files
YAML files
XML files
INI files
Enterprise Example
Without Templates
web01.conf
web02.conf
web03.conf
db01.conf
db02.conf
Every server requires its own configuration file.
Difficult to maintain.
With Templates
One template
httpd.conf.j2
Variables automatically generate
web01
web02
web03
db01
db02
Easier maintenance
Faster deployments
Standardized infrastructure
Jinja2
Definition
Jinja2 is the template engine used by Ansible.
Purpose
Replace variables.
Perform calculations.
Execute conditions.
Create loops.
Format text.
Build dynamic configuration files.
File Extension
.j2
Examples
httpd.conf.j2
nginx.conf.j2
sshd_config.j2
report.j2
Enterprise Directory Structure
Project Root
ansible.cfg
inventory
playbooks
roles
group_vars
host_vars
templates
files
handlers
logs
Templates Directory
templates
httpd.conf.j2
nginx.conf.j2
sshd_config.j2
hosts.j2
motd.j2
report.j2
index.html.j2
resolv.conf.j2
application.properties.j2
mysql.cnf.j2
Template Module
Purpose
Copy template
Replace variables
Render Jinja2
Preserve permissions
Preserve ownership
Module Name
template
Basic Syntax
name
Copy Apache configuration
template
src
templates/httpd.conf.j2
dest
/etc/httpd/conf/httpd.conf
Module Parameters
src
Source template
Relative to templates directory
dest
Destination path
owner
File owner
group
File group
mode
Linux permissions
backup
Backup old file
force
Replace existing file
validate
Validate configuration before replacing
attributes
Linux file attributes
follow
Follow symbolic links
unsafe_writes
Disable atomic write
Linux File Paths
Apache RHEL
/etc/httpd/conf/httpd.conf
Apache Ubuntu
/etc/apache2/apache2.conf
Nginx
/etc/nginx/nginx.conf
SSH
/etc/ssh/sshd_config
Hosts
/etc/hosts
DNS
/etc/resolv.conf
MOTD
/etc/motd
Systemd
/etc/systemd/system
Cron
/etc/cron.d
Variables in Templates
Basic Variable
ServerName {{ inventory_hostname }}
Variable Lookup
{{ ansible_hostname }}
{{ ansible_fqdn }}
{{ ansible_default_ipv4.address }}
{{ ansible_distribution }}
{{ ansible_distribution_version }}
{{ ansible_kernel }}
{{ ansible_processor_vcpus }}
{{ ansible_memtotal_mb }}
{{ ansible_date_time.date }}
{{ ansible_date_time.time }}
Inventory Variables
inventory_hostname
Inventory hostname
inventory_hostname_short
Short hostname
groups
Inventory groups
hostvars
Variables of every host
group_names
Current host groups
play_hosts
Hosts in play
ansible_play_hosts
Active hosts
ansible_limit
Limited hosts
Variable Syntax
Double Curly Braces
{{ variable }}
Examples
{{ server_name }}
{{ http_port }}
{{ document_root }}
{{ inventory_hostname }}
Example Apache Template
ServerName
{{ inventory_hostname }}
Listen
{{ apache_port }}
DocumentRoot
{{ document_root }}
ServerAdmin
{{ admin_email }}
Example Nginx Template
server_name
{{ inventory_hostname }}
listen
{{ nginx_port }}
root
{{ web_root }}
Example Report Template
Hostname
{{ inventory_hostname }}
IP Address
{{ ansible_default_ipv4.address }}
Operating System
{{ ansible_distribution }}
Kernel
{{ ansible_kernel }}
CPU
{{ ansible_processor_vcpus }}
Memory
{{ ansible_memtotal_mb }}
Filters
Purpose
Modify variable output
String Filters
upper
lower
capitalize
title
replace
trim
split
join
Number Filters
int
float
abs
round
List Filters
first
last
sort
unique
reverse
length
random
Default Filter
{{ variable | default('Unknown') }}
Replace Filter
{{ hostname | replace('-', '_') }}
Upper Filter
{{ hostname | upper }}
Lower Filter
{{ hostname | lower }}
Conditional Statements
if
Execute when condition is true
elif
Additional condition
else
Default action
endif
End condition
Example
If RedHat
Use httpd path
Else
Use apache2 path
Comparison Operators
Equal
Not Equal
Greater Than
Less Than
Greater Than or Equal
Less Than or Equal
Logical Operators
and
or
not
Loops
Purpose
Generate repeated configuration automatically.
Loop Types
for
endfor
Example
Multiple Virtual Hosts
Multiple DNS Servers
Multiple Users
Multiple Packages
Comments
Purpose
Documentation
Jinja Comment
Hidden after rendering
YAML Comment
Visible in playbook
Whitespace Control
Remove unnecessary blank lines
Improve configuration readability
Tests
defined
undefined
equalto
none
string
number
iterable
directory
file
Facts
Source
setup module
Common Facts
ansible_hostname
ansible_distribution
ansible_distribution_major_version
ansible_os_family
ansible_kernel
ansible_architecture
ansible_memory_mb
ansible_mounts
ansible_interfaces
ansible_processor
ansible_date_time
Host Variables
host_vars
web01.yml
web02.yml
db01.yml
Group Variables
group_vars
all.yml
webservers.yml
dbservers.yml
appservers.yml
Variable Precedence
Extra Variables
Task Variables
Block Variables
Role Variables
Play Variables
Host Variables
Group Variables
Inventory Variables
Facts
Role Defaults
Template Validation
Purpose
Prevent invalid configuration deployment.
Example
Apache
Validate before replacing
Nginx
Test configuration before restart
Backup
backup true
Create timestamped backup
Backup Location
Same directory
Original filename with timestamp
File Permissions
owner
root
group
root
mode
0644
0600
0755
0640
Linux Permission Meaning
0644
Owner read write
Group read
Others read
0600
Owner read write only
0755
Owner full access
Group read execute
Others read execute
File Ownership
chown equivalent
owner
group
Services After Template Deployment
Apache
Restart
Reload
Nginx
Restart
Reload
SSH
Restart
Systemd
daemon-reload
Handlers
Purpose
Restart service only when template changes.
Examples
Restart Apache
Restart Nginx
Restart SSH
Restart MySQL
Enterprise Workflow
Administrator creates template
Variables stored in inventory
Playbook calls template module
Jinja2 renders variables
Configuration generated
File copied to managed node
Validation executed
Backup created
Correct owner applied
Correct group applied
Correct permissions applied
Handler notified
Service restarted or reloaded
Verification completed
Enterprise Use Cases
Apache Deployment
Nginx Deployment
HAProxy Configuration
Keepalived Configuration
SSH Hardening
DNS Configuration
DHCP Configuration
Database Configuration
Application Deployment
Docker Configuration
Kubernetes Configuration
Monitoring Configuration
Logging Configuration
Firewall Configuration
Load Balancer Configuration
Proxy Configuration
Mail Server Configuration
CI CD Configuration
Backup Configuration
Security Compliance Configuration
Best Practices
Keep templates modular.
Store variables in group_vars and host_vars.
Never hardcode IP addresses.
Never hardcode passwords.
Validate configurations before deployment.
Use handlers instead of restarting services directly.
Keep permissions secure.
Use meaningful variable names.
Separate templates by application.
Backup important configuration files.
Test templates before production deployment.
Use version control.
Follow least privilege.
Maintain reusable enterprise templates.
Interview Questions
What is a template
What is Jinja2
Why use templates instead of copy module
Difference between template and copy
What is inventory_hostname
What are filters
What are facts
What is validate
What is backup
What is handler
What is variable precedence
Why use group_vars
Why use host_vars
What is default filter
How are templates rendered
How do templates improve enterprise automation