Can we filter inventories using Jinja filters?

Is it possible to filter inventories and sources using Jinja filters? As in, filters listed here: http://docs.ansible.com/ansible/latest/playbooks_filters.html

When I try to use the regex_search filter, I get this error:

jinja2.exceptions.TemplateAssertionError: no filter named ‘regex_search’

Specifically, I have tried to set the INSTANCE FILTERS field on my source to {{ config.name | regex_search(‘(.-test-.’) }}.

I am looking for a more flexible way to filter hosts than setting INSTANCE FILTERS to something like {{ “foo” in config.name }} can provide.

That’s probably not going to work, instance filters are specific to whatever inventory source you are using. Currently they are implemented on ec2 and vmware inventory sources and you can see more information here:

http://docs.ansible.com/ansible-tower/latest/html/userguide/inventories.html#amazon-web-services-ec2

http://docs.ansible.com/ansible-tower/latest/html/userguide/inventories.html#vmware-vcenter

That doesn’t really answer my question.

The INSTANCE FILTERS field appears to use the same {{}} syntax as a normal Ansible Template. Thus, I would think you’d be able to do anything in that field you can do in a template. At least as far as configuring what the stuff between the brackets turns into.

That’s why I’m wondering if I should be able to use the regex_search jinja filter. If I am, then the fact I got that error means there is a problem. If I’m not, then I just can’t use the filters and have to figure out another way of doing what I want.

Thanks!

David Reagan (jerrac@gmail.com) said:

That doesn't really answer my question.

The INSTANCE FILTERS field appears to use the same {{}} syntax as a normal
Ansible Template. Thus, I would think you'd be able to do anything in that
field you can do in a template. At least as far as configuring what the
stuff between the brackets turns into.

As Matt said, only for VMware... ec2 uses that field differently, and other
scripts not at all.

That's why I'm wondering if I should be able to use the regex_search jinja
filter. If I am, then the fact I got that error means there is a problem.
If I'm not, then I just can't use the filters and have to figure out
another way of doing what I want.

As long as your're just worried about VMware...

It does not use Ansible's custom filters.
See https://github.com/ansible/ansible/blob/devel/contrib/inventory/vmware_inventory.py#L136-L139
for the regex_match filter you can use.

Bill

Oh… Now I see how Matt answered my question…

So the answer to my question is that you can’t use just any jinja filter. You can only use specific filters that each kind of source supports.

Thanks!