Basics of Jinja2 Templating
Learn how to manage placeholders and add dynamic values in your Ansible configuration using Jinja2.
Introduction to Jinja2 templating
Jinja2 is a powerful templating engine used in Ansible for creating dynamic content in configuration files, templates, and playbooks. It allows us to insert variables, loops, conditional statements, and more into our Ansible tasks. Jinja2 template files usually have the .j2
extension, but it’s not compulsory to use it in our Ansible configuration.
Jinja2 delimiters
Jinja2 uses three major delimiters to indicate where it should process content and how to replace it:
- Variable substitution (
{{ }}
) - Embedding expressions and control statements (
{% %}
) - Comment (
{# #}
)
Variable substitution ({{ }}
)
The {{ }}
double curly braces are used for variable substitution. We can insert variable values into our templates and playbooks using this syntax. Here is an example:
---- name: Playbook 1hosts: web_serverstasks:- name: Display a variabledebug:msg: "Hello, {{ user_name }}"
In this example, {{ user_name }}
will be replaced with the actual value of the user_name
variable.
Embedding expressions and control statements ({% %}
)
Jinja2 uses the curly braces with a percentage sign {% %}
for embedding expressions and control statements. Below is an example:
---- hosts: web_serversvars:user_name: "DevOps"tasks:- name: Print a personalized greetingdebug:msg: "Hello, {% if user_name %}{{ user_name }}{% else %}Guest{% endif %}!"
In the above example, the debug
task will print a message with a personalized greeting based on the user_name
variable. If the user_name
is defined, it will print "Hello, John!"
; otherwise, it will print "Hello, Guest!"
.
Comment ({# #}
)
Any content enclosed within the {# #}
delimiter is treated as a comment and is ignored by the templating engine. Here is an example:
---- name: Playbook 3hosts: web_serverstasks:- name: Regular taskdebug:msg: "This is a message."- name: {# A comment #}debug:msg: "This won't be executed."
In the example above, ...