Use this when deciding how automation reacts to failures.
Error Handling
Error handling in automation decides what happens when a step fails: fail fast or continue, retry with backoff, time out, clean up, report clearly and leave systems in a known state.
1. Error handling: classify, retry transient errors, fail fast on fatal ones, clean up, report.
2. Never swallow errors.
3. Bound retries and timeouts.
4. Partial failures need reconciliation.
5. Report with context.
error → classify → retry/fail → cleanup → report
Context & applicabilityCommon mistakes · platform/version boundaries
Operational reference
Fast context before you go deeper.
Verification & Troubleshooting
Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.
Use the operational verification above to establish the expected state.
Capture the concrete output, symptom, packet, log or counter before changing anything.
Step 1 Target-state verification ladder Verify boundary
Error Handling uses a strict target-state ladder for failure classification, retry/compensation and terminal state: request accepted → job/task succeeded → target object changed → effective runtime state confirmed → original workload verified.
Step 2 Verification path Verify boundary
Verification must deliberately exercise failure behavior, not only happy paths. Trigger a known validation failure and show no target mutation occurs; trigger a transient/retryable failure and verify attempts, backoff and final outcome; trigger a post-mutation verification failure and verify the workflow reports partial/uncertain state rather than false success. For block/rescue-style systems, confirm rescue only handles the intended class and that always/cleanup runs when required. Capture the final target state independently after both successful and failed executions. Verify caller-visible exit/status semantics so schedulers and upstream workflows can distinguish recovered success from unresolved failure. A test that only sees an error message without checking state and return status is incomplete.
Step 3 Where it fails Narrow the fault
Failure boundaries are input/validation → controller/runtime → dependency/transport → target authorization/API → mutation/convergence → verification → cleanup/compensation. Handle the failure where its semantics are best understood; swallowing a target error in a generic wrapper destroys context. Retry only at one step where duplicate execution is safe or protected by idempotency/deduplication. A timeout creates uncertainty—work may continue after the caller gives up—so verify target state before retrying. Partial fan-out requires per-target recovery decisions. Never mark a run successful solely because rescue logic executed; success requires the intended final state or an explicitly accepted recovered state. Preserve the original failure and re-run the original consumer-facing check after remediation.
Evidence · 1 on this Topic
Expected observations and documentation recipes are reference material. Record actual output, device identity, scope and time before claiming a verified result.
Subtopics
Go one level deeper into this subject.
Exceptions are errors raised by code that can be caught and handled, such as try/catch/finally in PowerShell and Python.
Subtopic Exit CodesExit codes in error handling tell the caller whether automation succeeded: 0 for success, non-zero for distinct failures.
Subtopic Fail FastFail fast stops a job at the first serious error, such as set -e in Bash or $ErrorActionPreference = 'Stop', so it does not continue in an unknown state and do more damage.
Subtopic Continue on ErrorContinue on error lets a job proceed after a non-critical step fails, such as ignore_errors in Ansible or -ErrorAction Continue, while recording the failure so it is not missed.
Subtopic RetryRetry in error handling repeats a failed operation for transient problems like timeouts or HTTP 503, with a maximum count and backoff, such as until/retries in Ansible.
Subtopic BackoffBackoff increases the wait between retries, such as 1, 2, 4 and 8 seconds, often with random jitter, so retries do not overload a struggling service.
Subtopic TimeoutTimeouts in error handling stop operations that hang, such as a stuck API call or SSH session, and turn them into clear failures that can be retried or reported.
Subtopic Circuit BreakerA circuit breaker stops calling a failing dependency after repeated errors, fails fast for a cooling-off period, then tries again, protecting both the automation and the failing service.
Subtopic Partial FailurePartial failure is when a job succeeds on some targets and fails on others.
Subtopic CleanupCleanup removes temporary files, sessions, locks and partially created resources when a job ends or fails, using finally blocks, trap EXIT or always sections in playbooks.
Subtopic Failure ReportingFailure reporting tells the right people a job failed, with the step, target, error and log link, through notifications, tickets or monitoring, instead of a failure hidden in a log.
- Fail fast on serious errors.
- Retry only operations that are safe to repeat.
- Always clean up and report clearly.
- Error classification (retryable vs fatal) — handling
- Non-zero exit and clear message on failure — signal
- Cleanup on every exit path — safety
ReferenceWhy it matters1 section · depth on demand
In depth
Error handling decides what automation does when something fails: retry, skip, stop, roll back or alert. Explicit handling turns unexpected situations into predictable outcomes.
| Strategy | Use when |
|---|---|
| Retry with backoff | Transient errors (timeouts, 429, 503) |
| Fail fast | Invalid input, authentication failure |
| Continue and report | Independent items in a batch |
| Roll back | Partial changes would be harmful |
| Circuit breaker | Dependency is down |
Always surface the original error message and context in logs; generic "job failed" messages waste troubleshooting time.
ReferenceImportant terms & boundaries1 section · depth on demand
Mechanics
Automation Error Handling is control flow around failure semantics, not merely printing an error message. Distinguish syntax/validation failures, dependency/connectivity failures, rejected target operations, timeouts, partial completion and verification mismatches because each demands different behavior. A non-zero exit code or thrown exception is only one failure channel; APIs may return structured error objects, asynchronous jobs may fail after initial acceptance, and distributed operations may succeed on some targets and fail on others. Retry policy must understand whether an operation is idempotent and whether the failure is transient. Compensation/rollback is a separate operation that can itself fail. Good automation therefore models outcome states such as succeeded, failed-before-mutation, partially-mutated, recovered, recovery-failed and verification-failed instead of flattening all of them to success/failure.
ReferenceConfiguration & state1 section · depth on demand
Lifecycle
Define error contracts at module/job/workflow boundaries before production. Specify which failures are retryable, maximum attempts/backoff, overall timeout, cancellation behavior, cleanup, compensation and escalation owner. Avoid blanket “continue on error” or “ignore_errors” policies that convert unknown failures into false success. Preserve exceptions/error records with enough context to diagnose them, but redact credentials and sensitive payloads. Test failure paths as part of release testing, including dependency outage, permission denial, malformed input and mid-operation interruption. If a recovery path changes target state, version and test it like any other mutation logic. Changes to provider/API behavior or timeout defaults can alter failure semantics, so revisit the contract when dependencies change.
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Verification history & basis
When and against what this Topic was checked. Later text edits do not count as a new check.
Authoritative/upstream documentation reviewed for bounded claims in > Error Handling. Documentation verification only; this is not observed lab or production Evidence.
Basis: https://docs.ansible.com/projects/ansible/latest/playbook_guide/playbooks_error_handling.html · confidence 94%Quick lookup tables
→ Error Handling · operational reference
Context-specific ownership, verification, output and failure-boundary lookup for → Error Handling.
| Layer | Error Handling operational reference |
|---|---|
| Runtime/ownership | Automation error-handling patterns / Ansible current · identify controller/worker/target ownership before mutation |
| Persistent intent | Versioned configuration/playbook/workflow with explicit dependencies and least-privilege identity |
| Verification | ansible-playbook playbook.yml --check -vv; echo exit=$? |
| Expected interpretation | Failures are classified by boundary, retries are bounded, cleanup/compensation is explicit, and automation returns an outcome that callers can distinguish from partial success. |
| Recovery boundary | Preserve correlation IDs + pre-state, then verify target/service independently after remediation |
Deep reference
Healthy vs suspicious evidence
Output interpretation
Error output should carry a stable category/code, human message, operation/step identity, target/resource ID, correlation/execution ID, retry metadata, original underlying error and whether mutation may have occurred. Preserve structured exceptions or API error bodies before rendering them as console text. In fan-out jobs, keep per-target outcomes and an aggregate policy; do not lose the one failed node inside a global “completed” message. Report retry exhaustion differently from immediate non-retryable rejection. If compensation runs, record both original failure and compensation result. Logs should make it possible to answer “what changed before the failure?” and “what state remains now?” without replaying a risky operation.