Multiple conditions not working

I want to run few tasks in shell if they satisfy a condition. Strangely the task runs if the second condition is satisfied even though the first one fails.

name: ods
shell: “/something {{state}}”

when: ((ods) and (not (ansible_hostname | search(“demlh*”))))
register: sss_ods_out
notify: output ods
ignore_errors: yes

Here sss_ods is a variable defined in a vars file. If I remove the latter condition the task would run but I want both the conditions to be satisfied for the task to run and I can’t understand where am I going wrong.

The “when” stanza performs a AND when there are multiple when conditions (http://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html#the-when-statement).

Whenever I encounter a problem with ‘when’ I try to break it up to multiple lines so the numerous parenthesis aren’t causing confusion:

  • name: ods
    shell: “/something {{state}}”
    when:

  • ods

  • not (ansible_hostname | search(“demlh*”))

register: sss_ods_out
notify: output ods
ignore_errors: yes

With that you might be able to deduce why the “AND” clause isn’t working as expected.

It might also be that the “ansible_hostname | search(…)” might need to change to “ansible_hostname is search(…)” (change | to is).

If not, can you provide what “ods” contains? A simple “debug:” before that call should suffice.

I just noticed, if you break the when into two clauses, instead of doing “not (…)” you can do this:

  • name: ods
    shell: “/something {{state}}”
    when:

  • ods

  • ansible_hostname is not search(“demlh*”)

register: sss_ods_out
notify: output ods
ignore_errors: yes

You’re a hero! Splitting does the job. I still wonder why previous logic did not work.

I’ve run into subtle and hard-to-spot logic bugs (Ansible and elsewhere) that were ‘correct’ but magically solved when rewritten. I agree that your syntax looks spot on, but breaking it out into multiple statements might make it easier to troubleshoot later on too.

Glad it worked!