Use this when jobs must clean up after themselves.
Cleanup
Cleanup 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.
1. Cleanup on every exit path: temp files, locks, sessions, snapshots.
2. Use trap/finally/always.
3. Test failure paths.
4. Idempotent cleanup.
5. Log cleanup.
exit (success or failure) → cleanup → release
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 Verification path Verify boundary
The primary procedure is: Run success, controlled-failure and cancellation fixtures that each acquire a temporary resource; inspect both primary status and cleanup logs, then query that no owned resource/lock remains. Exercise failure-oriented cases such as exception in cleanup masking root cause, uninitialized handle cleanup, deleting shared temp paths, releasing another run’s lock, cancellation bypassing finalizers and retry repeating destructive cleanup so the test covers failure cases, not only the happy path.
Step 2 Common mistakes Narrow the fault
- Cleanup only on success.
Step 3 Where it fails Narrow the fault
Failure analysis for Error Handling → Cleanup should follow the path through the components: resource acquisition → main operation → success/error/cancel path → finally/defer/finalizer → external resource release → post-cleanup verification. Tests should include edge cases such as exception in cleanup masking root cause, uninitialized handle cleanup, deleting shared temp paths, releasing another run’s lock, cancellation bypassing finalizers and retry repeating destructive cleanup. Recovery should preserve primary and cleanup errors separately, determine resource ownership from correlation IDs, repair only leaked owned resources, then rerun failure/cancellation fixtures to show finalization.
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.
- Remove temp files, sessions, locks.
- Run cleanup on failure too.
- Use finally/trap/always.
trap cleanup EXIT— Bashfinally {} / always:— PowerShell/Ansible- Temp files, locks, sessions released — hygiene
ReferenceWhy it matters1 section · depth on demand
In depth
Cleanup removes temporary resources an automation run created — temp files, snapshots, sessions, locks, test VMs — whether the run succeeded or failed. Missing cleanup leaves clutter that consumes capacity and causes later conflicts.
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
- block:
- ansible.builtin.include_tasks: change.yml
always:
- ansible.builtin.include_tasks: cleanup.yml
Put cleanup in finally/always/trap blocks so it runs on failure too, and make it idempotent.
ReferenceImportant terms & boundaries1 section · depth on demand
Mechanics
Cleanup in Error Handling is owned at runtime by the automation runtime finalization path that releases temporary resources regardless of success, handled failure or cancellation. The durable intent is explicit cleanup contract listing owned temporary files/locks/sessions/leases/transactions and which cleanup steps are safe after partial initialization. Reliable automation must carry stable identity across the path: run ID plus resource IDs/handles created during that run. The consumer-visible target is ephemeral resources and locks owned by the run, not pre-existing shared resources unless ownership is confirmed. The key invariants are cleanup is idempotent, runs on all relevant exit paths, does not mask the primary error, does not delete resources it did not create and records partial cleanup failure separately.
ReferenceConfiguration & state1 section · depth on demand
Lifecycle
Store and review explicit cleanup contract listing owned temporary files/locks/sessions/leases/transactions and which cleanup steps are safe after partial initialization; pin or at least record implementation/model versions and keep environment-specific identity outside reusable logic where possible. The stable identity contract is run ID plus resource IDs/handles created during that run.
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 > Cleanup. Documentation verification only; this is not observed lab or production Evidence.
Basis: https://docs.python.org/3/tutorial/errors.html · confidence 94%Quick lookup tables
Error Handling → Cleanup · operational reference
Context-specific ownership, verification, output and failure-boundary lookup for Error Handling → Cleanup.
| Layer | Error Handling → Cleanup operational reference |
|---|---|
| Runtime/ownership | automation cleanup/finalization semantics · the automation runtime finalization path that releases temporary resources regardless of success, handled failure or cancellation |
| Persistent intent | explicit cleanup contract listing owned temporary files/locks/sessions/leases/transactions and which cleanup steps are safe after partial initialization |
| Verification | Run success, controlled-failure and cancellation fixtures that each acquire a temporary resource; inspect both primary status and cleanup logs, then query that no owned resource/lock remains. |
| Expected interpretation | Every path releases only resources owned by the run, primary errors remain visible, cleanup is safe to retry, and independent post-run checks show no leaked lock/session/temp object. |
| Recovery boundary | preserve primary and cleanup errors separately, determine resource ownership from correlation IDs, repair only leaked owned resources, then rerun failure/cancellation fixtures to prove finalization |
Deep reference
Healthy vs suspicious evidence
Output interpretation
At minimum retain run ID, primary status/error, acquired resource IDs, cleanup step/status, retry count, leaked-resource count and independent post-cleanup query result. The useful output makes ambiguity visible, links to the target identity from run ID plus resource IDs/handles created during that run, and provides enough context to safely decide whether a retry is permitted.