Ansible templates are a powerful feature that enables dynamic generation of configuration files and scripts during automation workflows. Using Jinja2 templating, Ansible templates allow for flexibility and adaptability in creating infrastructure and application configurations. This article explains what templates are, how they work, and their benefits.
What Are Ansible Templates?
Ansible templates are Jinja2-based files used to create dynamic configuration files or scripts. These templates can include variables, conditionals, loops, and filters, allowing for highly customized output tailored to the specific needs of managed systems.
Key Features:
- Dynamic Content: Generate files with runtime-specific data.
- Customization: Use variables and logic to create tailored configurations.
- Reusability: Write once and reuse templates across multiple tasks.
How Do Ansible Templates Work?
Templates are stored as .j2 files and processed using Ansible’s template module, which replaces variables and applies logic before deploying the file to the target system.
Example Template File
nginx.conf.j2:
``jinja2
server {
listen {{ nginx_port }};
server_name {{ nginx_server_name }};
location / {
root {{ nginx_root }};
index index.html;
}
}
`
Example Playbook Using a Template
`yaml
- name: Configure Nginx
hosts: webservers
vars:
nginx_port: 80
nginx_server_name: example.com
nginx_root: /var/www/html
tasks:
- name: Deploy Nginx configuration
template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
mode: 0644
`
This playbook:
1. Substitutes variables (e.g., {{ nginx_port }}) with their defined values.
2. Saves the rendered configuration file to /etc/nginx/nginx.conf.
Common Features of Templates
1. Variables:
Insert variables into templates for dynamic values.
`jinja2
server_name {{ nginx_server_name }};
`
2. Conditionals:
Add logic to generate conditional content.
`jinja2
{% if ssl_enabled %}
listen 443 ssl;
{% else %}
listen 80;
{% endif %}
`
3. Loops:
Use loops to iterate over lists or dictionaries.
`jinja2
upstream backend {
{% for server in backend_servers %}
server {{ server }};
{% endfor %}
}
`
4. Filters:
Transform data with Jinja2 filters.
`jinja2
upstream backend {
{{ backend_servers | join(' ') }}
}
`
5. Comments:
Use comments for clarity.
`jinja2
# This is a comment
``
Benefits of Ansible Templates
1. Dynamic Configuration:
Templates enable you to create files tailored to runtime conditions and variables.
2. Efficiency:
Avoid manual editing by automating the generation of configuration files.
3. Reusability:
Write a single template and reuse it for multiple hosts or environments.
4. Consistency:
Ensure