Templates
Notes// archive From the original Code Walker docs. Kept for reference, so some versions and commands may be out of date.
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:
- name: render template
template:
src: /tmp/j2-template.j2
dest: /tmp/dest-config-file.txtUse the “Ansible managed” string set in the ansible_managed directive.
Example:
ansible.cfg file:
ansible_managed = Ansible managedInclude the ansible_managed string inside a Jinja2 template:
{{ ansible_managed }}Using Loops
Jinja2 uses the for statement to provide looping functionality.
{% for user in users %}
{{ user }}
{% endfor %}Using Conditionals
Jinja2 uses the if statement to provide conditional control.
Example:
{% if finished %}
{{ result }}
{% endif %}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.