Loading

Quipoin Menu

Learn • Practice • Grow

ansible / Ansible Templates
tutorial

Ansible Templates

Configuration files often vary by host (e.g., different IP addresses, ports, or environment names). Hard‑coding these values is impossible. Ansible templates allow you to generate dynamic configuration files using the Jinja2 templating language.

What Are Templates?

A template is a text file containing variables and logic (loops, conditionals) that Ansible expands at runtime. Templates have the .j2 extension by convention. The template module copies the rendered result to the target host.

Templates turn static configuration files into dynamic, host‑specific ones.

Example: Nginx Virtual Host Template

Create a template file nginx.conf.j2:
server {
listen {{ http_port }};
server_name {{ server_name }};
root {{ doc_root }};
}
In your playbook, define variables and use the template module:
- name: Deploy nginx config
hosts: webservers
vars:
http_port: 8080
server_name: "{{ ansible_fqdn }}"
doc_root: /var/www/html
tasks:
- name: Render template to destination
template:
src: nginx.conf.j2
dest: /etc/nginx/conf.d/mysite.conf
notify: restart nginx

Using Loops in Templates

You can iterate over lists in Jinja2:
upstream backend {
{% for host in groups['appservers'] %}
server {{ host }}:8080;
{% endfor %}
}

Conditionals in Templates

Use {% if ... %} blocks:
{% if enable_ssl %}
listen 443 ssl;
ssl_certificate /etc/ssl/cert.pem;
{% endif %}

Testing Templates

You can test template rendering without applying changes using ansible with the template module’s --check or by using ansible localhost -m template -a "src=file.j2 dest=/tmp/test".


Two Minute Drill
  • Templates use Jinja2 syntax with {{ var }} and {% logic %}.
  • Use template module to render and copy to target.
  • Templates can include loops, conditionals, and access Ansible facts.
  • Name template files with .j2 extension.

Need more clarification?

Drop us an email at career@quipoinfotech.com