How to add multiple conditions for an ansible task? Here are some of the examples which will help you to pick the right one according to your need. Ansible is an open-source market-leading configuration management tool. It’s a complete automation tool that can be used from On-premise to cloud platforms. In some cases, ansible is used as a provisioning tool as well.
Here are some of the examples which will help you to add conditions while writing the playbook.
Simple condition:
The task will be executed, when the variable “VAR1” is equal to the “value1″.
- name: validate single variable shell: echo "Hello World" when: VAR1 == "value"
The task will be executed, when the variable “VAR1” is not equal to the “value1″.
- name: validate single variable shell: echo "Hello World" when: VAR1 != "value"
Multiple condition:
AND Operator:
The task will be executed, when the variable “VAR1” is equal to the “value1″ and “VAR2″ is equal to the “value2″.
- name: validate single variable shell: echo "Hello World" when: VAR1 == "value1" and VAR2 == "value2"
The task will be executed, when the variable “VAR1” is not equal to the “value1″ and “VAR2″ is equal to the “value2″.
- name: validate single variable shell: echo "Hello World" when: VAR1 != "value1" and VAR2 == "value2"
The task will be executed, when the variable “VAR1” is not equal to the “value1″ and “VAR2″ is not equal to the “value2″.
- name: validate single variable shell: echo "Hello World" when: VAR1 != "value1" and VAR2 != "value2"
OR Operator:
The task will be executed, when the variable “VAR1” is equal to the “value1″ or “VAR2″ is equal to the “value2″.
- name: validate single variable shell: echo "Hello World" when: VAR1 == "value1" or VAR2 == "value2"
The task will be executed, when the variable “VAR1” is not equal to the “value1″ or “VAR2″ is equal to the “value2″.
- name: validate single variable shell: echo "Hello World" when: VAR1 != "value1" or VAR2 == "value2"
The task will be executed, when the variable “VAR1” is not equal to the “value1″ or “VAR2″ is not equal to the “value2″.
- name: validate single variable shell: echo "Hello World" when: VAR1 != "value1" or VAR2 != "value2"
Multiple “AND” Condition & βORβ
The task will be executed, when the variable “VAR1” is equal to the “value1″ or “VAR2″ is not equal to the “value2″.
- name: validate mutliple variables shell: echo "Hello World" when: (VAR1 == "value1") or (VAR2 == "value2" and VAR3 == "value3")
Did you know ?
Conditions can be folded into multiple lines by using “>” symbol
Example:
- name: validate multiple variables shell: echo "Hello World" when: > (VAR1 == "value1") or (VAR2 == "value2" and VAR3 == "value3")
Hope this article is informative to you.
bammbr says
The “OR Operator” section is a bull shit. Check it.
Lingeswaran R says
Updated