0 / 13 lessons — 0%
Lesson 09 / 13
Loops & conditionals
Two small features do most of the heavy lifting in real playbooks: repeating a task over a list, and skipping a task unless some condition is true.
# loop — install several packages with one task, not five - name: Install required packages apt: name: "{{ item }}" state: present loop: - nginx - git - curl - htop
# conditional — only run on Debian-family hosts - name: Install nginx (Debian/Ubuntu) apt: name: nginx state: present when: ansible_facts['os_family'] == "Debian" - name: Install nginx (RedHat/CentOS) yum: name: nginx state: present when: ansible_facts['os_family'] == "RedHat"
Loops and conditionals combine freely — loop over a list of users, but only create the ones flagged as active:
- name: Create active users user: name: "{{ item.name }}" state: present loop: - { name: alice, active: true } - { name: bob, active: false } when: item.active
This is exactly why facts from lesson 5 matter:
when: ansible_facts[...] is how one playbook safely targets a mixed fleet of Ubuntu and CentOS boxes without maintaining two separate playbooks.Try it yourselfTake the package-install loop above and add a fifth package to the list. Rerun the playbook — only that one new package installs; the other four report "ok" (already satisfied) instead of reinstalling.