Introduction
In Ansible, a template is a text file that allows dynamic content generation using variables. It is commonly used to deploy configuration files that differ slightly across multiple servers without maintaining separate files for each.
1. What is a Template?
A template is a normal text file containing placeholders written using Jinja2 syntax (double curly braces).
ServerName {{ ansible_hostname }}
{{ variable_name }}: This value is replaced at runtime.- Example: Server 1 becomes
web-01, Server 2 becomesweb-02.
2. File Extension & Usage
- Templates typically use the
.j2extension (e.g.,apache.conf.j2). - The extension is not mandatory; Ansible identifies it as a template based on the module used.
3. The Template Module
To use templates, we use the template module in the playbook:
- name: Deploy Apache configuration
template:
src: apache.conf.j2
dest: /etc/apache2/apache.conf
4. Advanced Features (Jinja2 Logic)
You can use programming logic directly inside the template file:
Condition Example:
{% if ansible_os_family == "Debian" %}
PackageManager apt
{% endif %}
Loop Example:
{% for pkg in packages %}
Install {{ pkg }}
{% endfor %}
5. Key Advantages
- Reduces duplication: One template works for many servers.
- Consistency: Ensures standard configs across the infrastructure.
- Dynamic: Automatically inserts IP addresses, hostnames, or custom variables.
Final Summary
"In Ansible, templates are used to generate dynamic configuration files using Jinja2 syntax. The template module processes these files by replacing variables with actual values and deploying them to target systems, allowing a single configuration file to be reused across multiple servers."