What are conditionals?
Conditionals run a task only when a condition is true — OS-specific installs, environment gates, and dynamic automation.
Example: install Nginx only on Ubuntu servers.
when syntax
when: condition---
- name: Conditional example
hosts: all
become: true
tasks:
- name: Install nginx on Ubuntu
apt:
name: nginx
state: present
when: ansible_distribution == "Ubuntu"ansible-playbook playbooks/conditional.ymlMultiple conditions (AND)
A YAML list under when means all must be true:
- name: Run only on Ubuntu production
debug:
msg: "Production Ubuntu Server"
when:
- ansible_distribution == "Ubuntu"
- environment == "production"OR and NOT
when: ansible_distribution == "Ubuntu" or ansible_distribution == "Debian"
when: ansible_distribution != "CentOS"Restart only on Ubuntu
- name: Restart nginx
service:
name: nginx
state: restarted
when: ansible_distribution == "Ubuntu"Facts + conditions
Facts from Day 2 power most real when clauses:
when: ansible_os_family == "Debian"
when: ansible_memtotal_mb >= 2048Write when: var == "prod" — do not wrap the whole expression in {{ }}.
Interview: when executes a task only if the condition evaluates to true.