LOGBOOK

HELP

Quiz Entry - updated: 2026.11.12

How do register and when work together to restart httpd only if Postfix is running, and what makes the playbook from that example fail on a host where Postfix is stopped?

Register the result of systemctl is-active postfix and use when: result.rc == 0; but on a host where Postfix is stopped, the command exits non-zero, so the check task fails and the play stops before when is reached, unless the check is told not to fail.

On an active host rc is 0 and httpd restarts; on an inactive host rc is non-zero, the command task fails and the play stops unless failed_when false is set

* A non-zero exit code is a failure first and a condition second. *

- name: Restart HTTPD if Postfix is Running
  hosts: all
  tasks:
    - name: Get Postfix server status
      ansible.builtin.command: /usr/bin/systemctl is-active postfix
      register: result
      failed_when: false     # not in the original example; see below

    - name: Restart Apache HTTPD based on Postfix status
      ansible.builtin.service:
        name: httpd
        state: restarted
      when: result.rc == 0
  1. The first task asks systemd whether Postfix is active.
  2. register: result stores the module result, including rc, the command's exit code.
  3. The second task restarts httpd only if rc is 0, which systemctl is-active returns when the unit is active.

The pitfall: the command module treats any non-zero exit code as a failure. On a host where Postfix is inactive, systemctl is-active returns a non-zero code (usually 3), the first task fails, and Ansible stops running tasks on that host. The when condition that was meant to handle that case is never reached. Adding failed_when: false (or ignore_errors: true) makes "not active" a normal result. failed_when: false is the cleaner choice because the task then reports ok instead of a red, ignored failure, and the command only reads state, so changed_when: false fits as well.

Go deeper:

From Quiz: ITIA / Ansible Task Control: Loops, Conditionals, Handlers and Error Handling | Updated: Nov 12, 2026