Jinja2 filter list using string contains test

Question:

I’m trying to filter a list in ansible in Jinja2 when the elements contain a string, but the Jinja documentation doesn’t seem clear enough for me to figure it out.

This is what I have so far:

But all I get is the error:

So for example, if stdout_lines contains ["apples","running script one","oranges","running script two"], I want to print

They have documentation for select and documentation for built-in-tests, but they don’t display the “in” test, and I don’t know how they work in the context of this ansible variable.

I tried solving it like this:

But that displays “skipping” for every line that doesn’t pass the test … kinda defeating the purpose!

Answer:

The select filter would take another filter. Like in the docs odd, which will return only the odd elements of the list. The filter you would like to combine select with is equalto.

Now here’s the thing. Ansible bundles a very old version of Jinja2, which simply does not contain the equalto filter. Yes, that renders it useless unless you want to filter odd elements. (Which nobody ever in history wanted to…)

Furthermore I was yet unable to make custom filter plugins work in Ansible 2. So you’re pretty much forced to hack something ugly together.

helloV already showed one option. Here is another idea:


Update:

I recently discovered you can use match (not a standard Jinja2 filter but added by Ansible) together with select. Thats a good replacement for the eualto filter plus you can use regular expressions. This should work:

Leave a Reply