Ansible filters (ipaddr) in Python

Viewed 916

I am trying to use ansible filter (ipaddr) in python.

from ansible.plugins.filter import ipaddr
import jinja2

env = jinja2.Environment()
tmpl_string = """test : {{ '10.124.0.0'| ipaddr(-1) }}"""
tmpl = env.from_string(tmpl_string)
print(tmpl.render())

I am able to import the ipaddr filter with not any issues but when I am executing the code I am receiving following error:

jinja2.exceptions.TemplateAssertionError: No filter named 'ipaddr'.
1 Answers

You need to register a filter with Jinja in order to make it available in templates; see the Custom Filters section of the documentation. You want:

from ansible.plugins.filter import ipaddr
import jinja2

env = jinja2.Environment()

# tell jinja about the ipaddr filter
env.filters['ipaddr'] = ipaddr

tmpl_string = """test : {{ '10.124.0.0'| ipaddr(-1) }}"""
tmpl = env.from_string(tmpl_string)
print(tmpl.render())
Related