How to use `when` with multiple conditions?

0256

You can use the when clause with multiple conditions in Ansible by combining them with logical operators such as and and or. This allows you to create more complex conditional statements.

Example with and

- name: Install package if both conditions are true
  apt:
    name: package_name
    state: present
  when: ansible_os_family == "Debian" and ansible_distribution_version == "10"

In this example, the task will only run if both conditions are true: the OS family is Debian and the distribution version is 10.

Example with or

- name: Install package if either condition is true
  apt:
    name: package_name
    state: present
  when: ansible_os_family == "Debian" or ansible_os_family == "Ubuntu"

Here, the task will run if the OS family is either Debian or Ubuntu.

Combining Conditions

You can also combine and and or for more complex logic:

- name: Conditional task with multiple conditions
  apt:
    name: package_name
    state: present
  when: (ansible_os_family == "Debian" and ansible_distribution_version == "10") or ansible_os_family == "Ubuntu"

In this case, the task will run if the OS is Debian version 10 or if it is Ubuntu.

0 Comments

no data
Be the first to share your comment!