Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Mastering Ansible, 4th Edition - Fourth Edition

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

Product type Book
Published in Dec 2021
Publisher Packt
ISBN-13 9781801818780
Pages 540 pages
Edition 4th Edition
Languages
Authors (2):
James Freeman James Freeman
Profile icon James Freeman
Jesse Keating Jesse Keating
Profile icon Jesse Keating
View More author details

Table of Contents (18) Chapters

Preface 1. Section 1: Ansible Overview and Fundamentals
2. Chapter 1: The System Architecture and Design of Ansible 3. Chapter 2: Migrating from Earlier Ansible Versions 4. Chapter 3: Protecting Your Secrets with Ansible 5. Chapter 4: Ansible and Windows – Not Just for Linux 6. Chapter 5: Infrastructure Management for Enterprises with AWX 7. Section 2: Writing and Troubleshooting Ansible Playbooks
8. Chapter 6: Unlocking the Power of Jinja2 Templates 9. Chapter 7: Controlling Task Conditions 10. Chapter 8: Composing Reusable Ansible Content with Roles 11. Chapter 9: Troubleshooting Ansible 12. Chapter 10: Extending Ansible 13. Section 3: Orchestration with Ansible
14. Chapter 11: Minimizing Downtime with Rolling Deployments 15. Chapter 12: Infrastructure Provisioning 16. Chapter 13: Network Automation 17. Other Books You May Enjoy

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 2021 Publisher: Packt ISBN-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.
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 €14.99/month. Cancel anytime}