What are templates?
Templates are dynamic files generated from variables — Nginx configs, app env files, HTML pages, and more.
Instead of a separate static file per server, you keep one .j2 template and Ansible renders host-specific output.
templates/*.j2 + variables/facts → rendered file on managed node
Jinja2 variable syntax: {{ variable_name }}.
Create a template
mkdir -p templates
vim templates/index.html.j2<h1>Welcome to {{ app_name }}</h1>
<p>Host: {{ ansible_hostname }}</p>
<p>IP: {{ ansible_default_ipv4.address }}</p>Deploy with the template module
---
- name: Deploy dynamic page
hosts: all
become: true
vars:
app_name: DevOps Portal
tasks:
- name: Install nginx
apt:
name: nginx
state: present
- name: Render homepage
template:
src: templates/index.html.j2
dest: /var/www/html/index.html
mode: "0644"
notify: Restart nginx
handlers:
- name: Restart nginx
service:
name: nginx
state: restartedInventory variables in templates
[web]
node1 ansible_host=10.0.1.10 app_name=frontend
node2 ansible_host=10.0.1.11 app_name=backendEach host renders a different app_name from the same template.
Loops inside templates
<ul>
{% for pkg in packages %}
<li>{{ pkg }}</li>
{% endfor %}
</ul>Conditions inside templates
{% if env == "prod" %}
<p>Production mode</p>
{% else %}
<p>Non-production</p>
{% endif %}Dynamic Nginx snippet
{# templates/nginx.conf.j2 #}
server {
listen {{ app_port | default(80) }};
server_name {{ server_name }};
location / {
proxy_pass http://127.0.0.1:{{ backend_port }};
}
}Copy vs template
copy | template |
|---|---|
| Static file as-is | Renders Jinja2 first |
| Same content every host | Host/vars-specific content |
Interview: templates generate files dynamically using Jinja2 and Ansible variables/facts. Use template when content must change per host or environment.