Low Orbit Flux Logo 2 F

Ansible - Conditionals

When statement:




tasks:
  - name: "shut down Debian flavored systems"
    command: /sbin/shutdown -t now
    when: ansible_facts['os_family'] == "Debian"


Group conditions with parentheses ( logical or ):




tasks:
  - name: "shut down CentOS 6 and Debian 7 systems"
    command: /sbin/shutdown -t now
    when: (ansible_facts['distribution'] == "CentOS" and ansible_facts['distribution_major_version'] == "6") or
          (ansible_facts['distribution'] == "Debian" and ansible_facts['distribution_major_version'] == "7")


All true ( Logical and ):




tasks:
  - name: "shut down CentOS 6 systems"
    command: /sbin/shutdown -t now
    when:
      - ansible_facts['distribution'] == "CentOS"
      - ansible_facts['distribution_major_version'] == "6"


Ignore errors and conditional based on results:




tasks:
  - command: /bin/false
    register: result
    ignore_errors: True

  - command: /bin/something
    when: result is failed

  - command: /bin/something_else
    when: result is succeeded

  - command: /bin/still/something_else
    when: result is skipped


Convert to int to compare:




tasks:
  - shell: echo "only on Red Hat 6, derivatives, and later"
    when: ansible_facts['os_family'] == "RedHat" and ansible_facts['lsb']['major_release']|int >= 6


Convert non-bools to bools, check inverse, use ‘or’:




vars:
  epic: true
  monumental: "yes"
tasks:
    - shell: echo "This certainly is epic!"
      when: epic or monumental|bool
tasks:
    - shell: echo "This certainly isn't epic!"
      when: not epic


Check if var is defined:




tasks:
    - shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
      when: foo is defined

    - fail: msg="Bailing out. this play requires 'bar'"
      when: bar is undefined


Using when with a loop:




tasks:
    - command: echo {{ item }}
      loop: [ 0, 2, 4, 6, 8, 10 ]
      when: item > 5


Use default empty list for loop:




- command: echo {{ item }}
  loop: "{{ mylist|default([]) }}"
  when: item > 5


Loop over dict:




- command: echo {{ item.key }}
  loop: "{{ query('dict', mydict|default({})) }}"
  when: item.value > 5


Conditionals for importing things:




- import_tasks: tasks/sometasks.yml
  when: "'reticulating splines' in output"

- hosts: webservers
  roles:
     - role: debian_stock_config
       when: ansible_facts['os_family'] == 'Debian'


Checking string in a variable:




- import_tasks: tasks/sometasks.yml
  when: "'reticulating splines' in output"


Check membership in a dict:




  - name: set_fact when alice in key
    ansible.builtin.set_fact:
      alice_exists: true
    loop: "{{ lookup('ansible.builtin.dict', users) }}"
    when: "'alice' in item.key"