Skip to main content

Using Jinja2 Filters

1. Transforming Strings

Filter Description Example Result
capitalize Capitalizes the first letter of a string. "hello world"|capitalize "Hello world"
lower Converts a string to lowercase. "HELLO WORLD"|lower "hello world"
upper Converts a string to uppercase. "hello world"|upper "HELLO WORLD"
title Converts a string to title case. "hello world"|title "Hello World"
trim Removes whitespace from both ends of a string. " hello "|trim "hello"
replace Replaces occurrences of a substring. "hello world"|replace("world", "ansible") "hello ansible"

Example: Using replace filter

{% set message = "Hello world, welcome to Ansible" %}
{{ message|replace("Ansible", "Automation") }}

2. Working with Lists

Filter Description Example Result
first Returns the first item in a list. [1, 2, 3]|first 1
last Returns the last item in a list. [1, 2, 3]|last 3
length Returns the length of a list. [1, 2, 3]|length 3
reverse Reverses the order of a list. [1, 2, 3]|reverse [3, 2, 1]
unique Returns a list with duplicates removed. [1, 2, 2, 3]|unique [1, 2, 3]
join Joins list items with a separator. ["a", "b", "c"]|join(", ") "a, b, c"

Example: Using join filter

{% set items = ["apple", "banana", "cherry"] %}
{{ items|join(" and ") }}

3. Formatting Data

Filter Description Example Result
format Formats a string using Python's format method. "Hello {}"|format("World") "Hello World"
pprint Formats a data structure for readable output. {"a": 1, "b": 2}|pprint '{"a": 1, "b": 2}'
yaml_encode Encodes a value into YAML format. {"key": "value"}|yaml_encode "key: value"
json_query Queries JSON data using JMESPath syntax. '{"a": {"b": "c"}}'|json_query("a.b") "c"

Example: Using format filter

{% set name = "Ansible" %}
{% set version = "2.15" %}
{{ "Welcome to {} version {}"|format(name, version) }}

4. Providing Defaults

Filter Description Example Result
default Returns a default value if the input is undefined or empty. undefined_var|default("default value") "default value"
d Alias for default filter. undefined_var|d("fallback") "fallback"
mandatory Raises an error if the variable is undefined. undefined_var|mandatory Error

Example: Using default filter

{% set user = "admin" %}
{{ user|default("guest") }}

5. Combining Data

Filter Description Example Result
combine Merges dictionaries or lists. {"a": 1}|combine({"b": 2}) {"a": 1, "b": 2}
items2dict Converts a list of key-value pairs into a dictionary. [["a", 1], ["b", 2]]|items2dict {"a": 1, "b": 2}
list Converts a value to a list. "hello"|list ["h", "e", "l", "l", "o"]

Example: Using combine filter

{% set base = {"name": "ansible"} %}
{% set overrides = {"version": "2.15"} %}
{{ base|combine(overrides) }}

6. Selecting Items

Filter Description Example Result
select Selects items from a list based on a condition. [1, 2, 3, 4]|select("odd") [1, 3]
reject Rejects items from a list based on a condition. [1, 2, 3, 4]|reject("odd") [2, 4]
selectattr Selects items from a list based on an attribute condition. [{"a": 1}, {"a": 2}]|selectattr("a", "equalto", 1) [{"a": 1}]
rejectattr Rejects items from a list based on an attribute condition. [{"a": 1}, {"a": 2}]|rejectattr("a", "equalto", 1) [{"a": 2}]

Example: Using selectattr filter

{% set servers = [{"name": "server1", "status": "active"}, {"name": "server2", "status": "inactive"}] %}
{{ servers|selectattr("status", "equalto", "active") }}

7. Extracting Values

Filter Description Example Result
map Extracts a specific attribute from each item in a list. [{"name": "a"}, {"name": "b"}]|map("name") ["a", "b"]
extract Extracts a value from a dictionary or list. {"key": "value"}|extract("key") "value"
flatten Flattens nested lists. [[1, 2], [3, 4]]|flatten [1, 2, 3, 4]

Example: Using map filter

{% set users = [{"name": "alice"}, {"name": "bob"}] %}
{{ users|map("name") }}

8. Filtering Unique

Filter Description Example Result
unique Returns a list with duplicates removed. [1, 2, 2, 3]|unique [1, 2, 3]
uniqueby Returns a list with duplicates removed based on a key. [{"a": 1}, {"a": 1}]|uniqueby("a") [{"a": 1}]

Example: Using uniqueby filter

{% set items = [{"id": 1, "name": "item1"}, {"id": 2, "name": "item2"}, {"id": 1, "name": "item3"}] %}
{{ items|uniqueby("id") }}

9. Sorting Data

Filter Description Example Result
sort Sorts a list in ascending order. [3, 1, 2]|sort [1, 2, 3]
reverse Reverses the order of a list. [1, 2, 3]|reverse [3, 2, 1]
groupby Groups items in a list by a key. [{"a": 1}, {"a": 2}]|groupby("a") [[1, [{"a": 1}]], [2, [{"a": 2}]]]

Example: Using sort filter

{% set numbers = [3, 1, 4, 1, 5] %}
{{ numbers|sort }}

10. Working with IP Addresses

Filter Description Example Result
ipaddr Validates and converts an IP address string to a list of IP addresses. "192.168.1.1"|ipaddr ["192.168.1.1"]
ipwrap Wraps an IP address in brackets if it's IPv6. "2001:db8::1"|ipwrap "[2001:db8::1]"
ip2long Converts an IP address to its long integer representation. "192.168.1.1"|ip2long 3232235777

Example: Using ipaddr filter

{% set ip = "10.0.0.1" %}
{{ ip|ipaddr }}

11. Hashing Values

Filter Description Example Result
hash Generates a hash of a string using the specified algorithm. "password"|hash("sha256") hash of "password"
md5 Generates an MD5 hash of a string. "password"|md5 hash of "password"
sha1 Generates a SHA-1 hash of a string. "password"|sha1 hash of "password"

Example: Using md5 filter

{% set secret = "secret_key" %}
{{ secret|md5 }}

12. Manipulating Paths

Filter Description Example Result
basename Returns the basename of a path. "/home/user/file.txt"|basename "file.txt"
dirname Returns the directory name of a path. "/home/user/file.txt"|dirname "/home/user"
splitext Splits a path into root and extension. "/home/user/file.txt"|splitext ["/home/user/file", ".txt"]
realpath Resolves a path to its absolute form. "./file.txt"|realpath "/absolute/path/to/file.txt"

Example: Using basename filter

{% set path = "/etc/ansible/hosts" %}
{{ path|basename }}

Was this article helpful?