ansible Ansible: Loops and Conditionals When Condition


Example

Basic Usage

Use the when condition to control whether a task or role runs or is skipped. This is normally used to change play behavior based on facts from the destination system. Consider this playbook:

- hosts: all
  tasks:
    - include: Ubuntu.yml
      when: ansible_os_family == "Ubuntu"
    
    - include: RHEL.yml
      when: ansible_os_family == "RedHat"

Where Ubuntu.yml and RHEL.yml include some distribution-specific logic.

Another common usage is to limit results to those in certain Ansible inventory groups. Consider this inventory file:

[dbs]
mydb01

[webservers]
myweb01

And this playbook:

- hosts: all
  tasks:
    - name: Restart Apache on webservers
      become: yes
      service:
        name: apache2
        state: restarted
      when: webservers in group_names

This is using the group_names magic variable.

Conditional Syntax and Logic

Single condition

Syntax

when: (condition)

Example

  • when: ansible_os_family == "Debian"
  • when: ansible_pkg_mgr == "apt"
  • when: myvariablename is defined

Boolean Filter

Example

when: result|failed

Multiple Conditions

Syntax

When: condition1 and/or condition2

Example (simple)

when: ansible_os_family == "Debian" and ansible_pkg_mgr == "apt"

Example (complex)

Use parentheses for clarity or to control precedence. "AND" has a higher precedence than "OR".

Clauses can span lines:

when:
  ansible_distribution in ['RedHat', 'CentOS', 'ScientificLinux'] and
  (ansible_distribution_version|version_compare('7', '<') or
  ansible_distribution_version|version_compare('8', '>='))
  or
  ansible_distribution == 'Fedora'
  or
  ansible_distribution == 'Ubuntu' and
  ansible_distribution_version|version_compare('15.04', '>=')

Note the use of parentheses to group the "or" in the first distribution check.