skip to content

Live-Account Testing

Terratest-style tests apply a module into a throwaway account, assert on the live result and destroy it. Interviewers ask about teardown after a failed run, unique names and eventual consistency.

part ofTerraformread it →
on this pageshow

questions

6

With Terratest, what does a basic Go test of a Terraform module do, and why is the destroy deferred before `InitAndApply` runs?

level: juniorimportance: must knowfreq 45%

answer

  1. real binary, real account
  2. deploy, check, then remove
  3. apply helpers never destroy
  4. a failed apply can leave resources
  5. defer only counts once reached

basics

~20 s

A Terratest test runs real terraform init and apply in a sandbox account from Go, checks the live result, then destroys it. The destroy is deferred first because a failed apply stops the test and may have created resources.

solid answer

~40 s

A Terratest test is ordinary Go that runs the real `terraform` binary: `terraform.InitAndApplyContext` (the current form of `InitAndApply`) runs `init` and then `apply -input=false -auto-approve`, `terraform.OutputContext` reads an output, and the test asserts on the live result, such as an HTTP response. The apply helpers never destroy anything, so cleanup is the caller's job. I write `defer terraform.DestroyContext(t, ctx, options)` before the apply, because a failing apply stops the test at once and may already have created part of the module; a defer placed after it would never be reached. Deferred calls still run when the test fails through `t.Fatal`, so teardown survives ordinary failures. If I expect the failure, I call the `E` variant, which returns the error instead of failing the test.

code

go · 15 lines
go
func TestVpcModule(t *testing.T) {
	t.Parallel()
	ctx := t.Context()

	options := terraform.WithDefaultRetryableErrors(t, &terraform.Options{
		TerraformDir: "../examples/vpc",
		Vars:         map[string]any{"name": "vpc-test-" + strings.ToLower(random.UniqueID())},
	})

	defer terraform.DestroyContext(t, ctx, options)
	terraform.InitAndApplyContext(t, ctx, options)

	vpcID := terraform.OutputContext(t, ctx, options, "vpc_id")
	require.NotEmpty(t, vpcID)
}

go deeper

for a junior

Recall the four steps: configure options, defer the destroy, init and apply, check the live result. Be ready to say why the defer line comes before the apply line.

for a middle

Explain that the apply helpers stop the test on error and never clean up, and how the E and Context suffixes change that behaviour for a negative test or a timeout.

for a senior

Show that you know where the defer stops helping: a destroy that itself fails and a process that dies. Mention the account-level sweep that catches what the test could not remove.

for a principal

Treat the deferred destroy as a baseline every suite must follow, then ask how it is enforced across teams through review or shared helpers, since one careless test leaks money for everyone.

**Terratest** is a Go library for testing infrastructure code by deploying it for real. A test is an ordinary Go test function run by `go test`. It starts the installed `terraform` binary as a child process, creates real resources in a real account, checks that they work and then removes them. This answer follows Terratest 1.0.1, which needs Go 1.26 or newer. Terraform's own `terraform test` command is a separate framework and is not what this describes. ## The shape of one test Most tests follow the same four steps: 1. **Configure.** Build a `terraform.Options` value. `TerraformDir` points at the module or example folder, and `Vars` becomes `-var` arguments. 2. **Register the cleanup.** Call `defer terraform.DestroyContext(t, ctx, options)`. 3. **Deploy.** `terraform.InitAndApplyContext(t, ctx, options)` runs `terraform init` and then `terraform apply -input=false -auto-approve`, and returns the command's output. 4. **Validate.** Read values with `terraform.OutputContext`, then exercise the live system, for instance by sending an HTTP request to an endpoint the module exposes. The comment on the apply helpers says it plainly: they do not call destroy, and they assume the caller is responsible for cleaning up. If your test does not destroy what it created, the resources stay and keep costing money. ## Why the defer comes first Go's `defer` schedules a call to run when the surrounding function exits, whether it returns normally or stops on a failure such as `t.Fatal`. The catch is that a `defer` statement only takes effect once execution reaches it. Compare this order: ```go // Wrong: if the apply fails, the defer below is never reached. terraform.InitAndApplyContext(t, ctx, options) defer terraform.DestroyContext(t, ctx, options) ``` `InitAndApplyContext` stops the test on any error. That error does not mean nothing was created: Terraform may have finished several resources before the one that failed, and those remain. With the wrong order, the test exits leaving a partly deployed module and no cleanup registered. With the defer first, these cases are covered: - **The apply fails halfway:** destroy removes what was created. - **A later assertion fails:** destroy still runs, because the failure stops the test function and deferred calls run on the way out. - **Everything passes:** destroy runs last. Deferred calls run in reverse order of registration. That is useful: a log-fetching step deferred after the destroy runs before it, while the resources still exist. Terratest's own end-to-end example relies on this. ## Foo, FooE and the Context variants Most Terratest helpers come in up to four forms. Terratest 1.0 added the `Context` pair. | Form | Takes `context.Context` | On error | |---|---|---| | `Apply` | no | fails the test (deprecated) | | `ApplyE` | no | returns `error` (deprecated) | | `ApplyContext` | yes | fails the test | | `ApplyContextE` | yes | returns `error` | The table comes from two independent suffixes: - **`E`** means you get the error back and decide what to do. Use it when a failure is the expected result, as in a test proving that a bad input is rejected. - **`Context`** adds a context as the second argument, so you can pass cancellation and timeouts down to the child process. `t.Context()` is the documented default on Go 1.24 and later. - **Neither suffix** is what older code shows: `terraform.InitAndApply` still works, is marked deprecated and stays for the whole 1.x line. Use the form without `E` in most tests. It removes `if err != nil` noise, and a failed apply usually should fail the test. Reach for `E` only where the error itself is what you want to inspect. ## What the deferred destroy does not cover A `defer` needs a living Go process. If the destroy itself errors, `DestroyContext` fails the test and resources stay behind. If the process is killed outright, the deferred call never happens. Both cases need a second line of defence at the level of the account, so a deferred destroy is necessary but not sufficient. Also set the time limit. `go test` applies a default timeout of 10 minutes, which many infrastructure tests exceed, so the usual command passes `-timeout 30m`. Because Go can reuse a cached test result when the Go code has not changed, Terratest's docs also suggest `-count=1`: ```bash go test -count=1 -timeout 30m -p 1 ./... ```

  • When would you call `terraform.ApplyContextE` rather than `terraform.ApplyContext` in a Terratest test?
    When a failure is the expected result or you want to handle it yourself. `ApplyContext` fails the test on any error, which suits most tests. `ApplyContextE` returns the error, so a negative test can assert that a bad input is rejected. Keep the deferred destroy anyway, because a rejected apply may have created earlier resources.
  • Terratest 1.0 marks `terraform.InitAndApply` as deprecated. What changes when you move to `InitAndApplyContext`?
    Behaviour stays the same if you pass `context.Background()`, which is what the deprecated wrapper does. The new form takes a `context.Context` as its second argument, so cancellation and timeouts reach the Terraform child process. On Go 1.24 and later, the docs prefer `t.Context()`. The deprecated names keep working through 1.x and are due to go in 2.0.
  • What does `terraform.ApplyAndIdempotentContext` add to a plain Terratest apply?
    After the apply it runs a plan and fails the test if that plan still wants changes. That catches a configuration or provider that never settles, which a plain apply reports as success. It does not destroy anything, so it still needs the deferred `DestroyContext` before it.

  • InitAndApply destroys the resources it created when the Go test finishes.
  • Put the deferred destroy after the apply, once there is something to destroy.
  • A failed terraform apply creates nothing, so there is nothing to clean up.
  • Terratest mocks the provider, so a test does not need a cloud account.
  • ApplyContext and ApplyContextE differ only in which arguments they accept.
  • Deferred calls are skipped when a Go test fails through t.Fatal.
open as a page

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%

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.

open as a page

With Terratest, how do you stop parallel test runs in one sandbox account colliding on resource names and on Terraform's working files?

level: middleimportance: should knowfreq 38%

basics

~20 s

Expose resource names as module variables and feed them a random.UniqueID suffix, so runs do not clash on names. CopyTerraformFolderToTemp gives each test its own working directory, so .terraform and local state files stay separate.

open as a page

A Terratest test of a VPC module fails its endpoint check right after apply but passes on rerun: where do retries belong, and what should not be retried?

level: seniorimportance: should knowfreq 33%

basics

~10 s

Retry at two layers: terraform.WithDefaultRetryableErrors re-runs a Terraform command on listed transient errors, and http_helper or retry.DoWithRetryContext polls the live check. Deterministic failures should stop at once, and retries must fit the test timeout.

open as a page

Your organisation's Terratest suites apply real infrastructure into sandbox accounts: who should own those accounts and their bill, and what standing rules would you set?

level: principalimportance: should knowfreq 27%

basics

~20 s

A common answer: a platform team owns the sandbox accounts, guardrails and sweep, while each team writing tests sees and answers for its share of the bill. Standing rules cover isolation, naming, budgets, mandatory cleanup and leak reporting.

open as a page

With Terratest's `test_structure` package, how do you re-run only the validation step of a slow test without redeploying the module each time?

level: middleimportance: nice to knowfreq 25%

basics

~10 s

Wrap deploy, validate and teardown in test_structure.RunTestStage, then set SKIP_<stage> for each stage to skip. Save options to disk in the deploy stage and load them later, because a skipped stage's function never runs.

open as a page