Templates
Ansible uses the Jinja2 templating system for template files. Again, this is nice because you should be used to this from the FastAPI walk-through!
Variables and logic expressions are placed between tags, or delimiters.
Jinja2 templates use {% EXPR %}
for expressions or logic.
{{ EXPR }}
are used for outputting the results of an expression or a variable.
A Jinja2 template is composed of multiple elements: data, variables, and expressions.
Example:
# {{ ansible_managed }}
# DO NOT MAKE LOCAL MODIFICATIONS TO THIS FILE AS THEY WILL BE LOST
Port {{ ssh_port }}
ListenAddress {{ ansible_facts['default_ipv4']['address'] }}
A Jinja2 template for a configuration file can be deployed to the managed hosts using the template
module.
Example:
Use the “Ansible managed” string set in the ansible_managed
directive.
Example:
ansible.cfg
file:
Include the ansible_managed string inside a Jinja2 template:
Using Loops
Jinja2 uses the for statement to provide looping functionality.
Using Conditionals
Jinja2 uses the if statement to provide conditional control.
Example:
Variable Filters
The to_json
filter formats the expression output using JSON, and the to_yaml
filter formats the expression output using YAML.
{{ output | to_json }}
{{ output | to_yaml }}
{{ output | to_nice_json }}
{{ output | to_nice_yaml }}
Variable Tests
Built-in Ansible tests used to test return values include failed
, changed
,succeeded
, and skipped
.