Pcornel
Browse topics
Options
Recent
Favorites
Automation · Technical reference

Cleanup

Direct answer

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.

When to use this

Use this when jobs must clean up after themselves.

First 30 seconds

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.

Operational verification

exit (success or failure) → cleanup → release

Context & applicabilityCommon mistakes · platform/version boundaries
Platform / version applicability
automation cleanup/finalization semantics
applies
Structured applicability is explicit Topic metadata; it does not infer compatibility beyond the stored rows.
At a glance

Operational reference

Fast context before you go deeper.

Platformautomation cleanup/finalization semantics · Automation implementations are tool and platform specific. Use the adjacent Domain for the technology being automated and this Domain for automation behavior.
Scope / prerequisiteUse this when jobs must clean up after themselves.
What next?3 suggested next steps
Evidence1
On this pageJump to a specific section
Operational workflow

Verification & Troubleshooting

Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.

3 steps Observe → verify → isolate → change minimally → repeat the original test.
ObservedRecord what the original test actually shows

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 references

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.

observation · 1
Key points
  • Remove temp files, sessions, locks.
  • Run cleanup on failure too.
  • Use finally/trap/always.
Key checks
  • trap cleanup EXIT — Bash
  • finally {} / 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.

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.
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
Technical verification history

Verification history & basis

When and against what this Topic was checked. Later text edits do not count as a new check.

2026-09-14 · vendor docautomation cleanup/finalization semantics current concepts

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%
Embedded reference data

Quick lookup tables

Error Handling → Cleanup · operational reference

Context-specific ownership, verification, output and failure-boundary lookup for Error Handling → Cleanup.

LayerError Handling → Cleanup operational reference
Runtime/ownershipautomation cleanup/finalization semantics · the automation runtime finalization path that releases temporary resources regardless of success, handled failure or cancellation
Persistent intentexplicit cleanup contract listing owned temporary files/locks/sessions/leases/transactions and which cleanup steps are safe after partial initialization
VerificationRun 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 interpretationEvery 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 boundarypreserve primary and cleanup errors separately, determine resource ownership from correlation IDs, repair only leaked owned resources, then rerun failure/cancellation fixtures to prove finalization
Depth when you need it

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.

Confirmation

Confirm action

Continue?