ANSIBLE TEMPLATES

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 }}

2. File Extension & Usage

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

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."