Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to Templates in Ansible

What are Templates?

Templates in Ansible are files that contain variables and are used to generate configuration files dynamically. They are written in the Jinja2 templating language, which allows for the inclusion of dynamic content based on the variables passed to the template.

Why Use Templates?

Templates are useful for managing configurations in a scalable and maintainable way. They allow you to adjust configuration files dynamically, making it easier to manage different environments (e.g., development, staging, production) without duplicating code.

Basic Syntax of Jinja2

Jinja2 syntax is straightforward and allows you to include variables, loops, and conditional statements in your templates.

Here is an example of a basic Jinja2 template:

{{ '{{' }} variable_name {{ '}}' }}

This will be replaced by the value of variable_name when the template is rendered.

Creating a Template

Let's create a simple template for an Nginx configuration file:

server {
    listen 80;
    server_name {{ '{{' }} server_name {{ '}}' }};
    location / {
        proxy_pass http://{{ '{{' }} proxy_pass {{ '}}' }};
    }
}
                    

Using the Template Module

To use a template in an Ansible playbook, you can use the template module. Here is an example playbook that uses the above Nginx template:

- name: Configure Nginx
  hosts: webservers
  vars:
    server_name: example.com
    proxy_pass: 127.0.0.1:8080
  tasks:
    - name: Deploy Nginx configuration
      template:
        src: nginx.j2
        dest: /etc/nginx/sites-available/default
      notify:
        - restart nginx
                    

Handling Complex Logic

Jinja2 allows for complex logic, including loops and conditional statements:

Here's a more complex example:

{% if environment == 'production' %}
server {
    listen 80;
    server_name {{ '{{' }} server_name {{ '}}' }};
    location / {
        proxy_pass http://{{ '{{' }} proxy_pass {{ '}}' }};
    }
}
{% else %}
server {
    listen 8080;
    server_name {{ '{{' }} server_name {{ '}}' }};
    location / {
        proxy_pass http://{{ '{{' }} proxy_pass {{ '}}' }};
    }
}
{% endif %}
                    

Rendering the Template

When you run your playbook, Ansible will replace the variables and render the template based on the logic provided. Here is the command to run the playbook:

ansible-playbook -i inventory my_playbook.yml

Conclusion

Templates are a powerful feature in Ansible that can simplify the management of configuration files across different environments. By using Jinja2, you can include dynamic content, loops, and conditionals to create flexible and maintainable configurations.