Jinja2 Ansible Filters
Jinja2 Ansible Filters (current version 1.3.2) is a Python library that ports many of Ansible's Jinja2 filters, allowing them to be used independently without requiring the full Ansible core. This is particularly useful for projects needing specific Ansible-style data transformations within a standard Jinja2 templating environment. The library has a sporadic release cadence, with the last update in June 2022.
Warnings
- breaking Versions of `jinja2-ansible-filters` prior to 1.3.2 (released June 2022) were incompatible with Jinja2 versions 3.1 and later. This was due to internal Jinja2 filter decorators being renamed (`environmentfilter` to `pass_environment`), leading to import errors like 'cannot import name 'environmentfilter''.
- gotcha The `default` (or `d`) filter in Jinja2, including those provided by this library, by default only applies if a variable is *truly undefined*. It will NOT apply if the variable is defined but evaluates to a 'falsy' value (e.g., empty string `''`, `False`, `0`, or `None`).
- gotcha Ansible has historically deprecated and removed the ability to use 'Jinja tests' (e.g., `is failed`, `is successful`) with the filter pipe (`|`) syntax (e.g., `result | failed`). While this library provides filters, users accustomed to older Ansible patterns might incorrectly attempt this, leading to `AnsibleFilterError`.
- gotcha When chaining certain Jinja2 filters, particularly `map` or `selectattr` followed by `join`, the intermediate result might not be a list type that `join` expects directly. This can lead to unexpected output or errors.
Install
-
pip install jinja2-ansible-filters
Imports
- AnsibleEnvironment
from jinja2_ansible_filters import AnsibleEnvironment
Quickstart
from jinja2_ansible_filters import AnsibleEnvironment
# Create an environment that includes Ansible's Jinja2 filters
env = AnsibleEnvironment()
# Example 1: Use a basic filter (e.g., capitalize)
template1 = env.from_string("{{ 'hello world' | capitalize }}")
print(f"Capitalize: {template1.render()}")
# Example 2: Use a list filter (e.g., unique)
data = {'items': ['apple', 'banana', 'apple', 'orange']}
template2 = env.from_string("{{ items | unique | join(', ') }}")
print(f"Unique items: {template2.render(data)}")
# Example 3: Use a default filter
data2 = {'name': 'Alice'}
template3 = env.from_string("Hello {{ username | default('Guest') }}")
print(f"With defined var: {template3.render(username=data2['name'])}")
print(f"With undefined var: {template3.render()}")