Coder Perfect

Only run an Ansible job if the variable includes a particular string.

Problem

I have several jobs that are dependent on the value of variable1. I’m trying to see if the value is in variable1, but I’m getting an error:

- name: do something when the value in variable1
  command: <command>
  when: "'value' in {{variable1}}"

I’m working with Ansible 2.0.2.

Asked by mndhr

Solution #1

This should work if variable1 is a string and you’re looking for a substring within it:

when: '"value" in variable1'

Alternatively, if variable1 is an array or dict, it will look for the exact string as one of its items.

Answered by guido

Solution #2

None of the other solutions worked for me with Ansible 2.3.0.0, but this one did:

when: variable1 | search("value")

This is deprecated in Ansible 2.9 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]"

Answered by Denise Mauldin

Solution #3

From Ansible 2.5

when: variable1 is search("value")

Answered by imjoseangel

Solution #4

Some of the solutions are no longer valid.

Currently, I’m using ansible 2.6.x and this is what works for me.

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

Answered by Drew

Solution #5

Regex search is used in this example to execute a substring search.

- name: make conditional variable
  command: "file -s /dev/xvdf"
  register: fsm_out

- name: makefs
  command: touch "/tmp/condition_satisfied"
  when: fsm_out.stdout | regex_search(' data')

ansible version: 2.4.3.0

Answered by object

Post is based on https://stackoverflow.com/questions/36496911/run-an-ansible-task-only-when-the-variable-contains-a-specific-string