Search code examples
ansiblecasemultiple-conditionsansible-role.when

Unable to set multiple conditions in when clause for ansible roles


My ENV is DEV while the instance_name is myapp44

Thus, i want the role for myapp7 to skip as the when condition fails.

Below is my role that works fine and skips as the when clause fails.

- { role: myapp7, ENV: "{{ENV}}", ACTION: "{{ACTION}}", when: "'myapp7' in  instance_name" }

The issue is when i wish to test multiple condition using and condition. I expect it to fail and skip but the role gets invoked.

- { role: myapp7, ENV: "{{ENV}}", ACTION: "{{ACTION}}", when: ENV != 'perf' and "'myapp7' in  instance_name" }

The same issue is observed in the debug

   - debug:
       msg:  " Instance myapp7"
     when: "'myapp7' in instance_name"

   - debug:
       msg:  " Instance myapp7 with multi condition"
     when: ENV != 'perf' and "'myapp7' in  instance_name"
     tags: trigger

   - debug:
       msg:  " Instance myapp7 with brackets"
     when: (ENV != 'perf' and "'myapp7' in  instance_name")
     tags: trigger

I want all the three to fail but only the first condition fails in the above debug.

Can you please suggest how to write a multiple when condition for a role ?


Solution

  • You're over-quoting things. When you write:

    when: ENV != 'perf' and "'myapp7' in  instance_name"
    

    You are writing:

    when: (ENV != 'perf') and "a nonempty string"
    

    And a non-empty string always evaluates to true, so the second half of that expression is a no-op. You want:

    when: "ENV != 'perf' and 'myapp7' in  instance_name"
    

    I prefer to use alternate YAML quoting mechanisms for when expressions because I think it makes things easier to read. The following expression is exactly equivalent to the previous one:

    when: >-
      ENV != 'perf' and 'myapp7' in instance_name