Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Creating Templates in Ansible

Introduction

Templates in Ansible are used to manage configuration files. This tutorial will guide you through the process of creating and using templates in Ansible. By the end of this tutorial, you will be able to create a template, use variables within the template, and deploy the template to managed nodes.

Step 1: Setting Up Your Environment

Before you start creating templates, ensure you have Ansible installed. If you don't have it installed, you can install it using the following command:

sudo apt-get install ansible

Once Ansible is installed, you can create a new directory for your playbook:

mkdir ansible_templates

Navigate to the newly created directory:

cd ansible_templates

Step 2: Creating a Template File

Create a new directory called templates within your project directory:

mkdir templates

Next, create a new template file inside the templates directory. For this example, we'll create an Nginx configuration file:

nano templates/nginx.conf.j2

Inside the template file, you can use Jinja2 syntax to define variables. Below is an example template:

server {
    listen 80;
    server_name {{ server_name }};

    location / {
        proxy_pass http://{{ proxy_pass }};
    }
}

Step 3: Creating a Playbook

Now, create a new Ansible playbook file in your project directory:

nano deploy_nginx.yml

In the playbook file, you will define the tasks to copy the template to the managed nodes:

- name: Deploy Nginx configuration
  hosts: webservers
  vars:
    server_name: example.com
    proxy_pass: localhost:3000
  tasks:
    - name: Apply Nginx config template
      template:
        src: templates/nginx.conf.j2
        dest: /etc/nginx/sites-available/default
      notify:
        - Restart Nginx

  handlers:
    - name: Restart Nginx
      service:
        name: nginx
        state: restarted

In this playbook, we define variables server_name and proxy_pass that will be replaced in the template. The template module is used to copy the template to the destination path on the managed nodes.

Step 4: Running the Playbook

To execute the playbook, use the following command:

ansible-playbook deploy_nginx.yml

Ansible will replace the variables in the template and copy the final configuration file to the specified location on the managed nodes. If the configuration file changes, the Nginx service will be restarted.

Conclusion

Congratulations! You have learned how to create and use templates in Ansible. Templates provide a powerful way to manage configuration files dynamically. By using Jinja2 syntax, you can create flexible and reusable configuration files that can be easily deployed to multiple nodes.