Reader small image

You're reading from  Mastering Ansible, 4th Edition - Fourth Edition

Product typeBook
Published inDec 2021
PublisherPackt
ISBN-139781801818780
Edition4th Edition
Right arrow
Authors (2):
James Freeman
James Freeman
author image
James Freeman

James Freeman is an accomplished IT professional with over 25 years' experience in the technology industry. He has more than a decade of first-hand experience in solving real-world enterprise problems in production environments using Ansible, open source, and AWS. As part of this work, he frequently introduces Ansible as a new technology to businesses and CTOs for the first time. In addition, he has co-authored five books and one video training course on Ansible, facilitated bespoke Ansible workshops and training sessions, and presented at both international conferences and meetups on Ansible.
Read more about James Freeman

Jesse Keating
Jesse Keating
author image
Jesse Keating

Jesse Keating is an accomplished Ansible user, contributor, and presenter. He has been an active member of the Linux and open source community for over 15 years. He has firsthand experience involving a variety of IT activities, software development, and large-scale system administration. He has presented at numerous conferences and meetups, and has written many articles on a variety of topics.
Read more about Jesse Keating

View More author details
Right arrow

Chapter 6: Unlocking the Power of Jinja2 Templates

Manipulating configuration files by hand is a tedious and error-prone task. Equally, performing pattern matching to make changes to existing files is risky, and ensuring that the patterns are reliable and accurate can be time-consuming. Whether you are using Ansible to define configuration file content, perform variable substitution in tasks, evaluate conditional statements, or beyond, templating comes into play with nearly every Ansible playbook. In fact, given the importance of this task, it could be said that templating is the lifeblood of Ansible.

The templating engine employed by Ansible is Jinja2, which is a modern and designer-friendly templating language for Python. Jinja2 deserves its own book; however, in this chapter, we will cover some of the more common usage patterns of Jinja2 templating in Ansible to demonstrate the power it can bring to your playbooks. In this chapter, we will cover the following topics...

Technical requirements

To follow the examples presented in this chapter, you will need a Linux machine running Ansible 4.3 or newer. Almost any flavor of Linux should do; for those interested in specifics, all the code presented in this chapter was tested on Ubuntu Server 20.04 LTS unless stated otherwise, and on Ansible 4.3. The example code that accompanies this chapter can be downloaded from GitHub at https://github.com/PacktPublishing/Mastering-Ansible-Fourth-Edition/tree/main/Chapter06.

Check out the following video to view the Code in Action: https://bit.ly/3lZHTM1

Control structures

In Jinja2, a control structure refers to the statements in a template that control the flow of the engine parsing the template. These structures include conditionals, loops, and macros. Within Jinja2 (assuming the defaults are in use), a control structure will appear inside blocks of {% ... %}. These opening and closing blocks alert the Jinja2 parser that a control statement has been provided instead of a normal string or variable name.

Conditionals

A conditional within a template creates a decision path. The engine will consider the conditional and choose from two or more potential blocks of code. There is always a minimum of two: a path if the conditional is met (evaluated as true), and either an explicitly defined else path if the conditional is not met (evaluated as false) or, alternatively, an implied else path consisting of an empty block.

The statement for a conditional is the if statement. This...

Data manipulation

While control structures influence the flow of template processing, another tool exists that can help you to modify the contents of a variable. This tool is called a filter. Filters are the same as small functions, or methods, that can be run on the variable. Some filters operate without arguments, some take optional arguments, and some require arguments. Filters can be chained together as well, where the result of one filter action is fed into the next filter and then the next. Jinja2 comes with many built-in filters, and Ansible extends these with many custom filters that are available to you when using Jinja2 within templates, tasks, or any other place Ansible allows templating.

Syntax

A filter is applied to a variable by way of the pipe symbol, |, followed by the name of the filter, and then any arguments for the filter inside parentheses. There can be a space between the variable name and the pipe symbol, as well as a space...

Comparing values

Comparisons are used in many places with Ansible. Task conditionals are comparisons. Jinja2 control structures, such as if/elif/else blocks, for loops, and macros, often use comparisons; some filters use comparisons as well. To master Ansible's usage of Jinja2, it is important to understand what comparisons are available.

Comparisons

Like most languages, Jinja2 comes equipped with the standard set of comparison expressions you would expect, which will render a Boolean true or false.

The expressions in Jinja2 are as follows:

If you have written comparison operations in almost any other programming language (usually in the form of an if statement), these should all seem very familiar. Jinja2 maintains this functionality in templates, allowing for the same powerful comparison operations you would expect in conditional logic from any good programming language.

Logic

Sometimes, performing a single...

Summary

Jinja2 is a powerful language that is extensively used by Ansible. Not only is it used to generate file content, but it is also used to make portions of a playbook dynamic. Mastering Jinja2 is vital for creating and maintaining elegant and efficient playbooks and roles.

In this chapter, we learned how to build simple templates with Jinja2 and render them from an Ansible playbook. Additionally, we learned how to make effective use of control structures, how to manipulate data, and even how to perform comparisons and tests on variables to both control the flow of Ansible playbooks (by keeping the code lightweight and efficient) and create and manipulate data without the need for duplicate definitions or excessive numbers of variables.

In the next chapter, we will explore Ansible's capability in more depth to define what constitutes a change or failure for tasks within a play.

Questions

  1. Jinja2 conditionals can be used to render content inline with a playbook task.

    a) True

    b) False

  2. With of the following Jinja2 constructs will print an empty line each time it is evaluated?

    a) {% if loop.first -%}

    b) {% if loop.first %}

    c) {%- if loop.first -%}

    d) {%- if loop.first %}

  3. Jinja2 macros can be used to do which of the following?

    a) Define a sequence of keystrokes that need to be automated.

    b) Define a function for automating spreadsheets with Ansible.

    c) Define a function that gets called regularly from elsewhere in the template.

    d) Macros are not used in Jinja2.

  4. Which of the following is a valid expression for chaining two Jinja2 filters together to operate on an Ansible variable?

    a) {{ value.replace('A', 'B').lower }}

    b) {{ value | replace('A', 'B') | lower }}

    c) value.replace('A', 'B').lower

    d) lower(replace('A', 'B',value))

  5. Jinja2 filters always have mandatory arguments.

    a)...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Mastering Ansible, 4th Edition - Fourth Edition
Published in: Dec 2021Publisher: PacktISBN-13: 9781801818780
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (2)

author image
James Freeman

James Freeman is an accomplished IT professional with over 25 years' experience in the technology industry. He has more than a decade of first-hand experience in solving real-world enterprise problems in production environments using Ansible, open source, and AWS. As part of this work, he frequently introduces Ansible as a new technology to businesses and CTOs for the first time. In addition, he has co-authored five books and one video training course on Ansible, facilitated bespoke Ansible workshops and training sessions, and presented at both international conferences and meetups on Ansible.
Read more about James Freeman

author image
Jesse Keating

Jesse Keating is an accomplished Ansible user, contributor, and presenter. He has been an active member of the Linux and open source community for over 15 years. He has firsthand experience involving a variety of IT activities, software development, and large-scale system administration. He has presented at numerous conferences and meetups, and has written many articles on a variety of topics.
Read more about Jesse Keating