Skip to Content

How to use when statement in Ansible

When statement in Ansible

In Ansible, the “when” keyword is used to specify a condition or a set of conditions that must be met in order for a task to be executed. It allows you to add conditional logic to your Ansible playbooks and control the flow of execution based on certain conditions.

The “when” keyword is typically used in the “tasks” section of an Ansible playbook, where you define the tasks that need to be executed on remote hosts.

The syntax for using “when” in Ansible is as follows:

- name: Task Name
  module_name:
    module_arguments
  when: condition

The can be any valid expression that evaluates to a boolean value, either True or False. If the condition is True, the task will be executed; otherwise, it will be skipped.

You can use various built-in Ansible variables, module return values, or custom variables in your condition to make decisions based on different factors, such as host facts, inventory variables, or user-defined variables. For example, you can use the “ansible_distribution” fact to conditionally execute a task based on the operating system of the target hosts:

- name: Install package on CentOS
  yum:
    name: my_package
    state: present
  when: "'CentOS' in ansible_distribution"

In this example, the playbook is named “Install package on CentOS”. It contains a task that uses the “yum” module, which is a package manager for CentOS, to install a package named “my_package”. The “state” argument is set to “present”, indicating that the package should be installed if it is not already present on the system.

The “when” statement is used to define a condition under which this task will be executed. In this case, the condition is ‘CentOS’ in ansible_distribution, which is a Jinja2 expression that checks if the value of the “ansible_distribution” variable contains the string “CentOS”. The “ansible_distribution” variable is a predefined variable in Ansible that contains the name of the distribution of the target host, such as “CentOS”, “Ubuntu”, “Debian”, etc.

If the condition is evaluated as True, meaning the target host’s distribution is CentOS, the task will be executed, and the package “my_package” will be installed using the “yum” module. If the condition is False, meaning the target host’s distribution is not CentOS, the task will be skipped, and the package will not be installed.

Use variables in Ansible when statement

You can use variables in the “when” statement to define conditional expressions that depend on the values of variables.

- debug: 
    msg: the foo variable does not equal the bar string
  when: foo != 'bar'

In this case, the condition is foo != ‘bar’, which is a Jinja2 expression that checks if the value of the variable “foo” is not equal to the string “bar”.

If the condition is evaluated as True, meaning the value of “foo” is not equal to “bar”, the task will be executed, and the debug message will be printed. If the condition is False, meaning the value of “foo” is equal to “bar”, the task will be skipped, and no debug message will be printed.

The when parameter can also be used to compare a variable to another variable.

- name: Compare two variables
  hosts: localhost
  vars:
    var1: "hello"
    var2: "world"
  tasks:
    - name: Print message if variables are equal
      debug:
        msg: "The two variables are equal"
      when: "var1 == var2"

    - name: Print message if variables are not equal
      debug:
        msg: "The two variables are not equal"
      when: "var1 != var2"

In this example, the playbook compares two variables, “var1” and “var2”, using the “when” parameter in two different tasks. The first task prints a debug message if the two variables are equal, while the second task prints a debug message if the two variables are not equal.

The conditional expressions, “var1 == var2” and “var1 != var2”, are Jinja2 expressions that compare the values of the “var1” and “var2” variables. If the condition in the “when” statement is evaluated as True, the respective task will be executed and the debug message will be printed. If the condition is False, the task will be skipped and no debug message will be printed.

Use logical operators in Ansible when statement

You can also use logical operators such as “and”, “or”, and “not” in your conditions to create more complex expressions. For example:

Here are more examples of using the “when” keyword in Ansible:

- name: Compare variables with Jinja2 filters
  hosts: localhost
  vars:
    var1: "hello"
    var2: "world"
  tasks:
    - name: Print message if var1 is not a substring of var2
      debug:
        msg: "var1 is not a substring of var2"
      when: "'{{ var1 }}' not in '{{ var2 }}'"

    - name: Print message if var1 is not empty and var2 is uppercase
      debug:
        msg: "var1 is not empty and var2 is uppercase"
      when: "var1 != '' and var2 is uppercase"

In this example, the playbook uses Jinja2 filters to modify and compare the values of variables in the “when” parameter. The first task will be executed and the debug message “var1 is not a substring of var2” will be printed if the value of “var1” is not a substring of the value of “var2”. The second task will be executed and the debug message “var1 is not empty and var2 is uppercase” will be printed if the value of “var1” is not empty and the value of “var2” is in uppercase.

Using when with host facts:

- name: Execute task on Ubuntu hosts
  apt:
    name: my_package
    state: present
  when: "'Ubuntu' in ansible_distribution"

This task will only be executed on hosts with Ubuntu as the distribution.

Using when with variable comparison:

- name: Execute task when variable is not empty
  module_name:
    module_arguments
  when: my_variable is not empty

This task will only be executed if the variable “my_variable” is not empty.

Use multiple conditions in Ansible when statement

Using when with multiple conditions:

- name: Execute task when multiple conditions are met
  module_name:
    module_arguments
  when: 
    - "'CentOS' in ansible_distribution"
    - "'webserver' in inventory_hostname"

This task will only be executed if the target host’s operating system is CentOS and its hostname contains the string ‘webserver’.

Using when with complex logical expressions:

- name: Execute task when multiple conditions are met
  module_name:
    module_arguments
  when: 
    - "'CentOS' in ansible_distribution"
    - "'webserver' in inventory_hostname"
    - "'production' in inventory_group_names"

This task will only be executed if the target host’s operating system is CentOS, its hostname contains the string ‘webserver’, and it is a member of the inventory group ‘production’.

Using when with variable comparison and logical operators:

- name: Execute task when multiple conditions are met
  module_name:
    module_arguments
  when: 
    - "'CentOS' in ansible_distribution"
    - "'webserver' in inventory_hostname"
    - "'production' in inventory_group_names"
    - my_variable > 10

This task will only be executed if all the conditions are met: the target host’s operating system is CentOS, its hostname contains the string ‘webserver’, it is a member of the inventory group ‘production’, and the value of the variable “my_variable” is greater than 10.

Using when condition with dictionary length:

- name: Example 3
  hosts: localhost
  tasks:
    - name: Task with dictionary length condition
      module_name:
        module_arguments
      when: "'webserver' in inventory_hostname and my_dict | length > 3"
      vars:
        my_dict:
          key1: value1
          key2: value2
          key3: value3
          key4: value4

In this example, the task “Task with dictionary length condition” will be executed only if the inventory hostname contains the string ‘webserver’ and the length of the dictionary “my_dict” is greater than 3. The condition is specified using a combination expression and the “length” filter on a dictionary.

when the foo variable is defined or undefined (undefined can be prevented with the default filter) when: foo is defined

when: foo is undefined

when the foo variable or array is empty or not empty when: foo | length > 0

when: foo | length == 0

when the foo variable does or does not equal string hello or world when: foo == ‘hello’

when: foo != ‘world’

when the foo variable does or does not contain an integer when: foo | type_debug == ‘int’

when: foo | type_debug != ‘int’

when the foo variable does or does not contain a boolean when: foo | type_debug == ‘bool’

when: foo | type_debug != ‘bool’

when the foo variable does or does not equal boolean true or false when: foo == true

when: foo != false

when the foo variable or array does or does not contain string hello or world when: foo is search ‘hello|world’

when: foo is not search ‘hello|world’

when the content of the foo variable does or does not contain the content of the bar variable when: bar in foo

when: bar not in foo

when the foo variable or array does or does not contain boolean true when: true in foo

when: false not in foo

when the foo variable does or does not contain string hello or world with no whitespace when: foo is regex ‘^(hello|world)$’

when: foo is not regex ‘^(hello|world)$’

when the foo variable does or does not contain string hello (see regex_search) when: foo | regex_search(‘.*hello.*’)

when: not foo | regex_search(‘.*hello.*’)

when hostname in one or more groups when: inventory_hostname in ( groups[‘foo’] + groups[‘bar’] )