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.
* 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
- The first task asks systemd whether Postfix is active.
register: resultstores the module result, includingrc, the command's exit code.- The second task restarts httpd only if
rcis0, whichsystemctl is-activereturns 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:
Conditions based on registered variables (official docs) — the official version of this pattern uses
ignore_errors: truefor exactly this reason.Exit status (Wikipedia) — why 0 means success and anything else means "something else happened".