Skip to main content

Using Jinja2 template in Ansible

Introduction

Ansible, an open-source automation tool, simplifies complex orchestration and configuration management tasks. It uses a simple syntax written in YAML called playbooks. Jinja2 is a templating language for Python, which means it allows for dynamic content generation.

In Ansible, Jinja2 templates provide an efficient way to enable dynamic expressions and access variables. They are simple text files that we can use in Ansible to create files dynamically on remote nodes.

Understanding Jinja2 Templates

Jinja2 templates in Ansible are similar to Python data types, like lists, dictionaries, and strings. The Jinja2 template contains variables and/or expressions, which get replaced with values when the template is evaluated, and tags (% and #) which control the logic of the template.

Creating a Jinja2 Template

Let's look at how we can create a Jinja2 template. Open your favorite text editor and create a file named example.j2 with the following content:

Hello {{ name }}, Welcome to {{ place }}!

The {{ }} markers indicate a placeholder that will be replaced by actual variables' values.

Using Jinja2 Templates in Ansible Playbook

Now, let's use this Jinja2 template in an Ansible playbook. Create a new Ansible playbook named example_playbook.yml:

---
- hosts: localhost
vars:
name: 'John'
place: 'Ansible'
tasks:
- name: Use Jinja2 template
template:
src: /path/to/example.j2
dest: /path/to/output.txt

This playbook runs on localhost. The template module in the task loads the Jinja2 template example.j2 and replaces the variables with their respective values (in this case, name with 'John' and place with 'Ansible'), and then writes the output to output.txt.

Running the Playbook

You can run the playbook using the following command:

ansible-playbook /path/to/example_playbook.yml

Once the playbook execution is successful, you can check the output.txt file. It should contain:

Hello John, Welcome to Ansible!

Jinja2 Filters

One of the powerful features of Jinja2 templates in Ansible is filters. Filters let you transform the output, format data, do arithmetic, and more.

For instance, let's modify our example.j2 template to capitalize the name:

Hello {{ name|capitalize }}, Welcome to {{ place }}!

Now, even if you input the name in lowercase, the output will have the name capitalized.

Conclusion

Jinja2 templates are an incredibly powerful tool in Ansible, which allow you to dynamically generate content, reducing repetition and making your playbooks more efficient. With the use of variables and filters, you can manage and control complex configurations with ease.

Remember, practice is key when it comes to mastering Jinja2 templates in Ansible, so keep experimenting with different variables, filters, and templates.