How to define multiple when conditions in Ansible

In Ansible, the when statement is used to conditionally execute a task based on the outcome of a test. You can use multiple when statements in a task by using the and and or operators to join multiple tests.

To use multiple when statements with the and operator, you can use the and keyword followed by a test. For example, the following task will only run when both the variable var1 is equal to value1 and the variable var2 is equal to value2:

- name: Example task
command: echo "This task runs only when var1 is value1 and var2 is value2"
when: var1 == 'value1' and var2 == 'value2'

To use multiple when statements with the or operator, you can use the or keyword followed by a test. For example, the following task will run when either the variable var1 is equal to value1 or the variable var2 is equal to value2:

- name: Example task
command: echo "This task runs only when var1 is value1 or var2 is value2"
when: var1 == 'value1' or var2 == 'value2'

You can also use parenthesis to make the conditions more readable. For example

- name: Example task
command: echo "This task runs only when var1 is value1 or (var2 is value2 and var3 is value3)"
when: var1 == 'value1' or (var2 == 'value2' and var3 == 'value3')

You can also use complex conditions with jq and register

- name: Example task
shell: echo '{"key1":"value1","key2":"value2"}'
register: json_output
- name: Another task
command: echo "This task runs only when key1 is value1 and key2 is value2"
when: json_output.stdout | from_json | json_query('key1') == 'value1' and json_output.stdout | from_json | json_query('key2') == 'value2'

You can use when statement in many modules like command, shell, copy, template etc.

It’s important to remember that, when using multiple when statements, the tests are evaluated from left to right and the order of the tests can affect the outcome of the task.

Leave a Comment