Cyber Month Deal - up to 36% OFF

How to Create Ansible Templates [With Examples]

Published on May 26, 2023 Updated on Oct 22, 2024

Configuration management can be one of the most time-consuming tasks for Linux administrators. While plenty of tools can help with configuration management, they can come with a steep learning curve. Ansible helps solve that problem with a relatively simple IT automation and configuration management approach. Ansible templates add the power of variable expansion and conditional logic to the mix and can be a powerful addition to any Linux admin's skillset.

In this article, we'll walk through how to create and use templates in Ansible playbooks to help you hit the ground running with this powerful IT automation tool.

What is Ansible?

Ansible is an open-source (GPL-3.0 license) automation tool often used for Linux server configuration management and orchestration. Ansible emphasizes simplicity and ease of use as core design principles, and it has become a staple among Linux administrators. Common use cases for Ansible include server provisioning, configuring network appliances, and running commands across fleets of servers via SSH.

There are two basic types of systems required to use Ansible:

  • Control node- An Ansible control node is a computer running Ansible CLI tools. Almost any modern Linux system with Python installed can be a control node.
  • Managed nodes- Also known as hosts, managed nodes are the computers that are managed by a control node.

Ansible control nodes use an inventory to group hosts together. Playbooks are YAML files that define the tasks an Ansible control node runs against some or all of the hosts in an inventory.

What is an Ansible template?

Ansible templates are Ansible modules that use Jinja2 templating to enable dynamic variables, conditional logic, and loops to be used with playbooks. For example, administrators can use variable expansion with Ansible templates by defining dynamic variables inside double curly brackets like this: {{ variable_here }}. Similarly, they can use templates to iterate through a for loop or implement conditional logic with if statements.

Run your deployments in a scalable and cost-effective open cloud infrastructure. Cherry Servers' secure virtual private servers offer automatic scaling, flexible pricing, and 24/7 technical support. Our pre-defined Ansible module helps you automate the installation and configuration.

How to Create and Use Templates in Ansible Playbooks

In the example below, we'll create a basic Ansible template that expands two variables defined in an Ansible playbook. Then, we'll run the playbook from our control node and confirm it worked on the managed node.

Prerequisites

Before we begin, you'll need:

  • Access to the terminal of two Linux systems a control system and a managed node. We'll use Ubuntu 22.04 LTS. ** We recommend installing the latest updates with apt update -y && apt upgrade -y before you get started.
  • Root/sudo privleges
  • An Apache or nginx websever serving pages from /var/www/html on the managed node. A default installation is fine for this demo. Check out How to Install and Configure Apache Web Server on Ubuntu 20.04 for a deep dive on Apache web server configuration.

Install pip

pip ("pip installs packages") is a popular Python package manager. We'll use it to install Ansible on the control system in the next step, so if you don't already have pip installed, install it with this command:

sudo apt install python3-pip

Install Ansible

Now, we'll use pip to install Ansible on the control system with this command:

python3 -m pip install ansible --user ansible

Note that this method of installing Ansible will install it in the ~/.local/bin directory by default. This means the Ansible commands will not be in your $PATH. To ensure the Ansible command we will use later works, run this command to add the ~/.local/bin files to the current user's $PATH temporarily:

export PATH="$PATH:~/.local/bin"

For a deeper dive on setting environment variables, check out How to List, Set and Manage Linux Environment Variables.

Create an Ansible template

First, make a directory on the control system for our test files:

mkdir ~/ansibledemo

Change directory to the directory:

cd ~/ansibledemo

Now, use a text editor (e.g., nano or vim) to create a demo.j2 file with these contents:

<!DOCTYPE html>
<html>
<body>

<h1>Best Breakfast Items</h1>

<ul>

{% for breakfast_item in breakfast %}
    <li> {{ breakfast_item }} </li>

{% endfor %}

</ul>

{% set today = ansible_date_time['weekday_number'] | int %}
{% if today == 2 %}
    <p> Today is Tuesday, get a free coffe with your sandwich! </p>
{% else %}
    <p> Stop in today for the best breakfast in town! </p>
{% endif %}

</body>
</html>

This file is a basic HTML page that has a static "Best Breakfast Items" header, a bullet list of items that will be dynamically created by items in a breakfast list in the playbook, and an if condition that displays different text if the date the playbook is executed is Tuesday or a different day.

Create an Ansible hosts file

Ansible hosts files contain a list of servers Ansible manages. Use a text editor to create this hosts file on your control system:

[servers]
server1 ansible_host=192.168.2.11 ansible_connection=ssh ansible_user=demouser

Replace 192.168.2.11 with the IP address of your managed server and demouser with a user account on the managed server.

Create an Ansible playbook

Now, we'll create an Ansible playbook that calls the template. Use a text editor to create this playbook.yml file on the control system:

- name: Breakfast test
  hosts: servers
  vars:
    breakfast: ["Pepper and egg", "Coffee", "Giardiniera"]

  tasks:
  - name: Call template
    template:
     src:  ~/ansibledemo/demo.j2
     dest: /var/www/html/demo.html

This playbook runs against the servers defined in our hosts file, defines the breakfast_food and hot_drink variables, and creates a version of our source (src) template file at the destination (dest) /tmp/demotest.txt.

Discover how Tempesta, an open-source application delivery controller (ADC), leveraged Cherry Servers' bare metal cloud to complete tests and validation of their ADC successfully, benefiting from 99.97% uptime, server customization, and 24/7 technical support.

Run the Ansible playbook

Note: For our demo example, we'll install sshpass and use password authentication. For production and other environments that require higher levels of security, we recommend configuring and using SSH keys.

Install sshpass on the control system so we can use password authentication to the managed server:

sudo apt install sshpass

Run the playbook with this command:

ansible-playbook -i hosts playbook.yml --ask-pass

Enter your password at the prompt, and then you should see output similar to: Run Ansible template

Verify the results

To confirm the playbook ran and the variable expansion worked as expected, browse to http://localhost/demo.html on the managed node.

You should see this output if the playbook did not run on Tuesday (based on the managed node's timezone):

Ansible template output 1

And this output if the playbook ran on Tuesday:

Ansible template output 2

Conclusion

That's it! Now you know the basics of Ansible templates, you can move on to more advanced use cases. For a deeper dive, we recommend reading the official templating docs and the Jinja template designer documentation.

Cloud VPS - Cheaper Each Month

Start with $9.99 and pay $0.5 less until your price reaches $6 / month.

Share this article

Related Articles

Published on Jul 26, 2022 Updated on Feb 6, 2024

How To Use Variables in Ansible Playbooks

Learn how to define and reference Ansible variables in playbooks, inventories or on the command line.

Read More
Published on Jul 27, 2022 Updated on Feb 6, 2024

How To Define and Use Handlers in Ansible Playbooks

Ansible handlers allow specific tasks to run only when the state of a system changes. Learn how to define and use handlers in your Ansible playbooks.

Read More
Published on Sep 16, 2024 Updated on Sep 16, 2024

How Does When Condition Work in Ansible

Learn how the when condition works in Ansible to control task execution based on variables, facts, and conditions. Optimize your playbooks with this detailed guide.

Read More
We use cookies to ensure seamless user experience for our website. Required cookies - technical, functional and analytical - are set automatically. Please accept the use of targeted cookies to ensure the best marketing experience for your user journey. You may revoke your consent at any time through our Cookie Policy.
build: 06ac5732e.831