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 ClauseAdd 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, RedHatansible_distribution– e.g., Ubuntu, CentOSansible_processor_coresansible_memtotal_mbansible_hostname
ansible localhost -m setupExample: 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 RegisterYou 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.existsMultiple 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
whenconditionally runs a task.- Use facts like
ansible_os_familyfor 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
