Custom Jinja tests?

Hi,

Custom template filters are a great way to take the programming out of my playbooks. Sometimes I would like to have a Jinja test, though.

For example, I have a filter ‘is_in_zone(domain, zone)’ to see if a domain ends with a certain tail. For example, ‘test.example.com’ is in zone ‘example.com’ (and in ‘com’).

{{ domain | is_in_zone(zone) }} would look nicer as {{ domain is in_zone(zone) }}, and having it as a test would also make it possible to use it in ‘select’ filters.

Is it possible to create custom Jinja tests? If not, where in the code should I look if I want to take a stab at adding that feature?

Regards,
Joost

What you are describing is a Jinja2 filter.

Read about filter plugins here and search the source tree for “core.py” for plenty of examples.

http://docs.ansible.com/developing_plugins.html

Also this is also a topic for ansible-devel :slight_smile:

It’s international join-ansible-devel advocacy day!

https://groups.google.com/forum/#!forum/ansible-devel

Additionally you could achieve this using the regex “|search” filter or even the python string method .endswith()

Moving to ansible-devel. :slight_smile:

[Moved from ansible-project.]

Additionally you could achieve this using the regex "|search" filter or even
the python string method .endswith()

Thanks for that, indeed. That fixes my use-case.

Do you think tests are never needed?

What you are describing is a Jinja2 filter.

Not really. Filters cannot be used in 'is' expressions or 'select'
filters. (I do realize that the distinction is small, and many times a
filter will do very nicely.)

Let me demonstrate with the 'search' filter. The first of the tasks in
this playbook succeeds while the second one fails:

- hosts: all
  gather_facts: no
  tasks:
  - debug: msg=filter
    when: "'foo.example.com' | search('\\.example\\.com$')"

  - debug: msg=test
    when: "'foo.example.com' is search('\\.example\\.com$')"

Granted, Jinja tests are basically syntactic sugar for filters, but
they are nice sometimes.

Is there interest in supporting custom tests?

Regards,
Joost

Ok, so they are filters.

You’d still write a filter plugin, you would just either return the value directly passed in or raise an exception.

Which is I’m guessing exactly what the filters do.