skip to content

A Terratest job applied a VPC module into a sandbox account, the CI runner was killed mid-test, and resources remain: why did the deferred destroy not run, and how do you contain such leaks?

level: seniorimportance: must knowfreq 42%

answer

  1. defer needs a living process
  2. a ten-minute default nobody chose
  3. state on the runner dies too
  4. nested time limits, innermost first
  5. a sweep that needs no state

basics

~20 s

A Go defer runs only while the test process lives, so a killed runner or Go's 10-minute default timeout skips it. Contain leaks with a generous -timeout, per-run remote state and a scheduled account-level cleanup.

solid answer

~40 s

`defer` is a Go language feature: it runs when the test function exits, including after `t.Fatal`, but not when the process dies. A killed runner never reaches it. Neither does Go's `-timeout`, which defaults to 10 minutes and aborts the test binary, cleanup included, so I set something like `go test -timeout 30m` and keep that inside the CI job's own limit. With local state, `terraform.tfstate` dies with the runner too, so nothing can run `destroy` afterwards; a remote backend with a per-run key through `BackendConfig` lets a later job replay it. That can still miss a resource being created at the moment of the kill, so the last layer works on the account: a scheduled job, such as the nightly cloud-nuke run Terratest's docs describe, which sweeps the sandbox without needing any state.

code

go · 20 lines
go
func TestVpcModule(t *testing.T) {
	// Expires before go test -timeout 30m would abort the binary.
	deployCtx, cancel := context.WithTimeout(t.Context(), 20*time.Minute)
	defer cancel()

	id := strings.ToLower(random.UniqueID())
	options := terraform.WithDefaultRetryableErrors(t, &terraform.Options{
		TerraformDir: "../examples/vpc",
		Vars:         map[string]any{"name": "terratest-vpc-" + id},
		BackendConfig: map[string]any{
			"bucket": "sandbox-test-state",
			"key":    id + "/terraform.tfstate",
			"region": "eu-west-1",
		},
	})

	// t.Context(), not deployCtx: an expired context would stop the destroy starting.
	defer terraform.DestroyContext(t, t.Context(), options)
	terraform.InitAndApplyContext(t, deployCtx, options)
}

go deeper

for a junior

Recall that defer runs when a Go function exits but not when the process is killed, and that go test has a 10-minute default timeout you normally raise.

for a middle

Explain which endings run the deferred destroy and which do not, and why local state on the runner makes a later terraform destroy impossible.

for a senior

Lay out the layers: nested time limits, a separate context for destroy, per-run remote state and an account sweep with an age filter. Say honestly that each layer still misses something.

for a principal

Treat leaks as a measured failure rate. Decide who owns the sweep, what counts as an acceptable leak count, and when repeated runner losses justify changing the runner setup.

Go's `defer` belongs to the running program. It schedules a call for when the surrounding function exits. If the process stops existing, nothing is left to make that call. Terratest's cleanup depends on that mechanism, so it can only be as durable as the Go process running it. ## What a deferred destroy survives | How the test ends | Does the deferred destroy run? | |---|---| | An assertion fails or `t.Fatal` fires | Yes | | The apply fails partway | Yes, if the defer was registered first | | `go test` reaches its `-timeout` | No: the whole test binary is aborted | | The runner is killed or its host is lost | No | | The CI job hits its own limit | Usually no, as the job is stopped from outside | | The context passed to destroy has already expired | The call happens, but `terraform destroy` never starts | A seventh case is easy to forget: destroy runs and fails. `DestroyContext` then fails the test, and the resources stay. ## Nest the time limits The most common cause is self-inflicted. Go's default test timeout is **10 minutes**, and Terratest's docs warn that when it fires, even your cleanup code will not run. Infrastructure tests often take longer, so set the limits deliberately, innermost first: 1. **A context deadline on deploy and checks**, for example 20 minutes. When it expires, the Terraform child process is ended and the test fails normally, so the Go process lives on to run the defer. 2. **`go test -timeout`**, for example 30 minutes. It covers the whole test binary, so it has to leave room for the destroy that follows that deadline. 3. **The CI job's own limit**, longer than `-timeout`, so the outer layer never fires first. Do not hand the deploy context to the destroy. Terratest's retry wrapper checks `ctx.Err()` before each attempt, so with an expired deadline `terraform destroy` never starts. Pass a separate context, as in the example below. An ended Terraform process can also lose track of a resource being created at that moment, so this reduces leaks without removing them. CI systems may also kill a job that prints nothing for a while. Terratest's docs recommend `logger.Log` and `logger.Logf`, which write to stdout immediately, plus `-p 1` when testing several packages, because Go otherwise holds output until a package's tests finish. ## Make the state survive the runner A local backend keeps `terraform.tfstate` in the working folder on the runner. If the runner disappears, the record of what was created goes with it, and nobody can run `terraform destroy` later. Two changes help: - **A remote backend with a per-run key.** Pass it through `BackendConfig`, for example `id + "/terraform.tfstate"`, so a follow-up job can run `terraform destroy` against that key. - **A way to find orphaned keys.** A key with no matching finished job is a list of runs to clean up. This is still not complete, for two reasons: - A resource still being created when the process died may be in no state file. - A remote backend receives intermediate snapshots at intervals during an apply, so the stored copy can lag behind. Terratest passes `-lock=false` unless `Options.Lock` is true, so by default a killed run leaves no stale lock to clear with `terraform force-unlock`. The same default means nothing stops a replayed destroy racing a test that is still alive, so confirm the job is dead first. ## Clean up at the account level The last layer does not depend on the runner or on state. Terratest's docs describe running **cloud-nuke** nightly in the maintainers' test AWS account to remove leftovers. Whichever tool you use, a sweep needs these properties: - **It runs somewhere other than the test runner**, on a schedule of its own. - **It ignores anything younger than the longest allowed test**, so it does not delete a live run. - **It can only reach sandbox accounts.** An account-wide delete is safe only in an account holding nothing else, which is one more reason tests belong in a separate account. - **It reports what it removed.** A rising count is an early sign of unstable runners or a broken test, and it should reach a person.

  • A Terratest deferred destroy ran but failed, leaving resources behind. What do you do next?
    `DestroyContext` fails the test, so the run goes red and someone can look. With `WithDefaultRetryableErrors`, errors matching its patterns have already been retried, so this failure is probably real, such as a dependency blocking deletion. With remote state, fix the cause and run `terraform destroy` again against that key. Otherwise the account-level sweep is what remains.
  • With Terratest, why must the context deadline, `go test -timeout` and the CI job limit be nested in that order?
    Only the innermost one leaves a living Go process able to run the deferred destroy. If `-timeout` fires first, the test binary is aborted with its cleanup. If the CI limit fires first, the job is stopped from outside. So each outer limit must allow enough time for the destroy that follows the inner limit.
  • Which `-lock` value does Terratest pass by default, and what does that mean when replaying a destroy for a killed run?
    `Options.Lock` is a plain bool that defaults to false, so Terratest passes `-lock=false` to apply and destroy. A killed run therefore leaves no stale lock to clear. It also means nothing stops a replayed destroy racing a run that is still alive, so check the original job has really ended. Setting `Lock: true` reverses both.

A deferred destroy is a note to switch off the lights as you leave the room. It works however you walk out, even in a hurry, but not if the building loses power with you inside. The account-level sweep is the caretaker who walks the floors each night.

  • A deferred destroy still runs when the CI runner is killed.
  • Go's test timeout fails only the slow test, and its cleanup code still runs.
  • Go's default test timeout can safely be left alone for infrastructure tests.
  • Sharing one deadline context between deploy and destroy is harmless.
  • A later terraform destroy always cleans up because state records every resource.
  • An account-wide cleanup job is safe in an account that also holds production.