Templating is a very nice feature of Ansible. It solves the common need to change multiple lines in a file based on a given situation. In this lesson, we'll learn more about templates, variables, and how they combine to make our lives so much easier.
Templates are just plain files. Much like you would copy a configuration file from your local machine to the remote machine, templates perform in a similar way. There are two main differences between templates and files though. As you might expect, for templates, we use the “template” module instead of the “copy” module. Secondly, templates replace parts of the template file with the values of variables.
Ansible uses the Python template engine called Jinja2, which you can read up about at the Jinja project homepage for syntax details.
Variables can come from a lot of different places, including automatically from the inventory, defaults, groups, along with values we explicitly set. We'll keep things simple in this lesson and only use variables we specify outright.
Variables are typically identified by double curly braces, like “” for example. You can put these curly braces in a lot of locations, either as we have been in some of our playbooks, and also in templates.
Use in Playbooks
To use templates, let's start things off simply with a template file. There's no purpose other than to illustrate how templates work. Save this as “template.j2” which ends in “j2” to represent Jinja 2.
# Regular Variable # If / Else Hyperdrive is enabled! # Loop
First, we can see three elements. First is a regular find and replace. The next is a conditional if/else statement. Finally, we have a loop that repeats its contents for every item in a given variable list. Let's take a look at the playbook that supplies these variables.
--- - name: Demonstrate Templates hosts: all vars: regular_variable: Find and Replace use_hyperdrive: false mylist: - steak - butter - eggs tasks: - name: Upload Template template: src=template.j2 dest=~/template.output sudo: false
There we have it. The “vars” section provides the variables to the template automatically by Ansible. All we need to do is add a new task that utilizes the template module, provide it with a source file (our template), a destination, and all the rest is taken care of for us. The output after the template has been processed with those variables looks like this:
# Regular Variable Find and Replace # If / Else Hyperdrive is not enabled # Loop I need to buy steak I need to buy butter I need to buy eggs
That's it on templates for now. In future posts, we'll see how precedence is calculated between all the levels of variable definition, how to access host variables, and more.