Jinja2 Ansible Filters

1.3.2 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

Initialize a Jinja2 environment using `AnsibleEnvironment` to automatically load the provided filters, then render templates with various Ansible-style filters.

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()}")

view raw JSON →