Templating in Ansible allows dynamic expressions and access to variables. It is used in tasks, defaults/variables files, and templates to generate configuration files or other text-based formats. Templating occurs before tasks are executed using the Jinja2 templating language which supports tags, flow control, filters and more. Examples demonstrate templating tasks, variables files, and templates to dynamically generate configuration files using variables and expressions.
4. What is templating
● Allows dynamic expressions and access to variables
● Used in
○ Tasks
○ Defaults/Variables
○ Templates
● Happens before the task is sent for execution to target machine
● Using Jinja2 language
5. Jinja2 language
● Modern and designer-friendly templating language for Python
● Heavily inspired by Django and Python
● Generates any text-based format
● Consists of tags
○ {% %} - statement
○ {{ }} - expression
○ {# #} - comment
● Tags can contain
○ Flow controls
■ if / else
■ for
○ Filters
○ ...
22. Example - templates file
{% for sect, opts in myfile_config.iteritems() %}
{# This is the section #}
[{{ sect }}]
{% for opt, val in opts.iteritems() %}
{# This is the key-value #}
{{ opt }}={{ val }}
{% endfor %}
{% endfor %}
# /etc/myfile.cfg
[section1]
option11=value11
option12=value12
23. Example - templates file
{% for sect, opts in myfile_config.iteritems() %}
{# This is the section #}
[{{ sect }}]
{% for opt, val in opts.iteritems() %}
{# This is the key-value #}
{{ opt }}={{ val }}
{% endfor %}
{% endfor %}
# /etc/myfile.cfg
[section1]
option11=value11
option12=value12
24. Example - templates file
{% for sect, opts in myfile_config.iteritems() %}
{# This is the section #}
{# #}[{{ sect }}]
{% for opt, val in opts.iteritems() %}
{# This is the key-value #}
{# #}{{ opt }}={{ val }}
{% endfor %}
{% endfor %}
# /etc/myfile.cfg
[section1]
option11=value11
option12=value12
25. Example - templates file
# /etc/myfile.cfg
[section1]
option11=value11
option12=value12
{% for sect, opts in myfile_config.iteritems() %}
{#- This is the section -#}
[{{ sect }}]{{ "n" }}
{%- for opt, val in opts.iteritems() %}
{#- This is the key-value -#}
{{ opt }}={{ val }}{{ "n" }}
{%- endfor %}
{% endfor %}
26. Example - templates file
# /etc/myfile.cfg
[section1]
option11=value11
option12=value12
{% for sect, opts in myfile_config.iteritems() %}
{#- This is the section -#}
[{{ sect }}]{{ "n" }}
{%- for opt, val in opts.iteritems() %}
{#- This is the key-value -#}
{{ opt ~ "=" ~ val ~ "n" }}
{%- endfor %}
{% endfor %}
27. Example - templates file
# /etc/myfile.cfg
[section1]
OPTION11 = value11
OPTION12 = value12
{% for sect, opts in myfile_config.iteritems() %}
{#- This is the section -#}
[{{ sect }}]{{ "n" }}
{%- for opt, val in opts.iteritems() %}
{#- This is the key-value -#}
{{ opt | upper ~ myfile_config_sep ~ val ~ "n" }}
{%- endfor %}
{% endfor %}