Lesson 13 / 26

Loops and Conditionals

Repeat a task over a list with loop and skip it with when.

loop and when

loop: runs a task once per item of a list, exposing the current value as item. when: runs a task only if a condition is true; otherwise the result is skipping. The condition is a Jinja2 expression written without braces, such as env == "production" or ansible_os_family == "Debian". Combine conditions with and, or and not.

Decide, repeat, react

Conditions, loops, handlers and tags give playbooks logic without turning them into scripts.

Three tools: when, loop, notify.
Figure 4.1 — when, loop and notify.

Loop and skip, run

I ran vars.yml (shown in the previous section) with its default env: staging: the loop prints three installs, and the production-only task is skipped.

ansible-playbook -i inventory.ini vars.yml

Output:

ok: [web1] => (item=git) => {
    "msg": "install git"
ok: [web1] => (item=curl) => {
    "msg": "install curl"
ok: [web1] => (item=nginx) => {
    "msg": "install nginx"
skipping: [web1]

Do not over-script

If a playbook is full of nested conditions, consider splitting it into roles or using variables to express the difference. Complex logic is hard to test and review.

Quick check: What result do you see when a `when:` condition is false?

  • changed
  • skipping
  • failed
  • unreachable
Answer

skipping — A task whose condition is false is skipped for that host.