Loading

Quipoin Menu

Learn • Practice • Grow

ansible / Conditionals
tutorial

Conditionals

Sometimes you want a task to run only under certain conditions – for example, only on a specific operating system, or only if a file exists. Ansible conditionals give you that control.

The when Clause

Add a when statement to a task. The task runs only if the condition evaluates to true.
- name: Shut down Debian systems
command: /sbin/shutdown -t now
when: ansible_os_family == "Debian"

Common Conditionals

Ansible provides many built‑in facts (gathered by setup module). Use ansible_facts or the short variable names:
  • ansible_os_family – e.g., Debian, RedHat
  • ansible_distribution – e.g., Ubuntu, CentOS
  • ansible_processor_cores
  • ansible_memtotal_mb
  • ansible_hostname
View all facts:
ansible localhost -m setup

Example: Install Apache on RHEL, Nginx on Debian

- name: Install web server
hosts: all
become: yes
tasks:
- name: Install nginx on Debian
apt:
name: nginx
state: present
when: ansible_os_family == "Debian"

- name: Install httpd on RedHat
yum:
name: httpd
state: present
when: ansible_os_family == "RedHat"

Using when with Variables and Register

You can test variables or registered results:
- name: Check if file exists
stat:
path: /etc/myapp.conf
register: myapp_config

- name: Only run if config exists
command: /usr/bin/validate_config
when: myapp_config.stat.exists

Multiple Conditions

Use logical operators:
when: ansible_distribution == "Ubuntu" and ansible_distribution_major_version == "20.04"
Or:
when: ansible_os_family == "Debian" or ansible_os_family == "RedHat"


Two Minute Drill
  • when conditionally runs a task.
  • Use facts like ansible_os_family for OS‑specific tasks.
  • Check registered results with when: result.stat.exists.
  • Combine conditions with and/or.

Need more clarification?

Drop us an email at career@quipoinfotech.com