Run an Ansible task only when the variable contains a specific string

Solution 1:

If variable1 is a string, and you are searching for a substring in it, this should work:

when: '"value" in variable1'

if variable1 is an array or dict instead, in will search for the exact string as one of its items.

Solution 2:

None of the above answers worked for me in ansible 2.3.0.0, but the following does:

when: variable1 | search("value")

In ansible 2.9 this is deprecated in favor of using ~ concatenation for variable replacement:

when: "variable1.find('v=' ~ value) == -1"

http://jinja.pocoo.org/docs/dev/templates/#other-operators

Other options:

when: "inventory_hostname in groups[sync_source]"

Solution 3:

From Ansible 2.5

when: variable1 is search("value")

Solution 4:

Some of the answers no longer work as explained.

Currently here is something that works for me in ansible 2.6.x

 when: register_var.stdout is search('some_string')