Advanced Jinja2 Techniques
In this final step, we'll explore some advanced Jinja2 techniques, including macros and filters. Macros are reusable template snippets, similar to functions in programming languages.
Create a new template file named advanced.j2
:
cd ~/project/templates
nano advanced.j2
Add the following content:
{% macro render_list(title, items) %}
{{ title }}:
{% for item in items %}
- {{ item }}
{% endfor %}
{% endmacro %}
1. Using a macro:
{{ render_list("Fruits", fruits) }}
{{ render_list("Vegetables", vegetables) }}
2. Using set:
{% set greeting = "Hello, " + name + "!" %}
{{ greeting }}
3. Custom filter (defined in playbook):
{{ complex_data | to_nice_json }}
4. Whitespace control:
{% for item in fruits -%}
{{ item }}
{%- if not loop.last %}, {% endif %}
{%- endfor %}
5. Raw block (no processing):
{% raw %}
This {{ will_not_be_processed }}
{% endraw %}
6. Include another template:
{% include 'simple_include.j2' %}
Now, let's create the simple include file. Create a new file named simple_include.j2
:
nano simple_include.j2
Add the following content:
This is content from an included template.
Current user: {{ ansible_user_id }}
Now, let's create a playbook to use this advanced template. Go back to the project root and create a new file named use_advanced.yml
:
cd ~/project
nano use_advanced.yml
Add the following content:
---
- name: Use advanced Jinja2 techniques
hosts: localhost
vars:
name: "Ansible Expert"
fruits:
- apple
- banana
- cherry
vegetables:
- carrot
- potato
- broccoli
complex_data:
key1: value1
key2:
- item1
- item2
custom_filters:
to_nice_json: "{{ '(' ~ ((complex_data | to_json) | replace('\"', '\\\"')) ~ ')' | from_json | to_nice_json }}"
tasks:
- name: Create file from template
template:
src: templates/advanced.j2
dest: /tmp/advanced.txt
- name: Display file contents
command: cat /tmp/advanced.txt
register: file_contents
- name: Show file contents
debug:
var: file_contents.stdout_lines
This playbook demonstrates advanced Jinja2 techniques, including macros, custom filters, whitespace control, and including other templates.
Run the playbook:
ansible-playbook use_advanced.yml
The output will show you how these advanced Jinja2 techniques work in practice.