Templating with Jinja2
In this lesson, you will learn how to use Jinja2 for templating in Ansible. Templating is a powerful feature in Ansible that allows you to dynamically generate files based on variables. This is particularly useful for configuration files that differ slightly between hosts.
By the end of this lesson, you'll be able to create a Jinja2 template for an HTML file that includes the host's name, and update your first_playbook.yml to use this template. We will use the nginx application installed on managed-node-1 and managed-node-2 for this purpose.
Creating a Jinja2 Template
Jinja2 templates in Ansible allow you to create text files, such as HTML, where the content of the file can change depending on the variables. Let's create a Jinja2 template for an HTML file which displays the hostname of the server.
Start by navigating to the templates directory inside the webserver role.
cd ~/code/roles/webserver/
Now let's move our oldindex.htmlfile from the files directory into the templates directory:
mv files/index.html templates/index.html.j2
Open this file with a text editor:
nano templates/index.html.j2
Let's update the file to include our {{ ansible_hostname }} variable like so:
Here, {{ ansible_hostname }} is a variable provided by Ansible which will be replaced with the actual hostname of the server where the template is deployed.
Updating the First Playbook
Next, we need to modify the role's main.yml to ensure the nginx role is installed and to deploy our new template to the web servers. In the next step, we are going to use the template ansible module. Re…
No comments yet. Add the first comment to start the discussion.