Integration testing with Terratest
Terratest is a Go library that applies real Terraform, checks the result and destroys it. When it beats terraform test, and its 2026 versions.
terraform test: the native testing frameworkMock providers and fast unit tests
Integration testing with Terratest
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Terratest tests are ordinary Go tests that run init and apply, read outputs, assert and destroy.
- defer the destroy so it runs even when an assertion fails; a killed CI job skips deferred code, so run a janitor for tagged test resources.
- Choose Terratest over terraform test when you need SSH, long HTTP retries, custom cloud API checks or Go control flow.
- Terratest reached v1.0.0 in May 2026 and v2.0.0 in September 2026 with /v2 module paths; older tutorials use names now marked deprecated.
When the question is “does it actually work”
A module can pass every plan-time test and still deploy a load balancer that returns 502. The security group is wrong in a way no schema can see, or the user data script has a typo, or the health check path does not exist. The only way to know is to build it, call it and tear it down. That is an integration test, and for years the standard tool for it has been Terratest, a Go library from Gruntwork.
You might ask why you need it when terraform test can run command = apply. The honest answer is that sometimes you do not. terraform test can apply, read outputs and, as HashiCorp’s tutorial shows, use the http provider in a later run to hit an endpoint. Terratest earns its place when the check is hard to express as HCL: SSH into a host and run a command, retry an HTTP call for five minutes while a service warms up, query the AWS API for something Terraform does not output, test several modules in parallel with real Go control flow.
The shape of a Terratest test
A Terratest test is an ordinary Go test. It points at a directory of Terraform code, applies it, reads outputs, asserts, and destroys. The Terratest repository’s own basic example, from the v1.0.1 tag, which I read on GitHub, has this shape (trimmed):
func TestTerraformBasicExample(t *testing.T) {
t.Parallel()
terraformOptions := terraform.WithDefaultRetryableErrors(t, &terraform.Options{
TerraformDir: "../examples/terraform-basic-example",
Vars: map[string]interface{}{"example": "test"},
NoColor: true,
})
defer terraform.DestroyContext(t, t.Context(), terraformOptions)
terraform.InitAndApplyContext(t, t.Context(), terraformOptions)
actual := terraform.OutputContext(t, t.Context(), terraformOptions, "example")
assert.Equal(t, "test", actual)
}
I did not compile or run this. Go is installed on this machine, but running it would mean downloading Terratest and its dependencies and executing them, and I did not want to execute downloaded code. The point of the shape is the order:
defer ... Destroycomes first in the code but runs last. Go’sdeferruns when the test function returns, whether the assertions passed, failed or panicked. That is how you avoid orphaned cloud resources after a red test.InitAndApplyrunsterraform initandterraform applyand fails the test on any error.Outputreads what the module exposes, and ordinary Go assertions check it.
WithDefaultRetryableErrors makes Terratest retry on a list of known flaky errors, such as network blips while downloading providers. t.Parallel() lets several tests run at once, each with its own copy of resources. Give each test unique names, because two tests creating a bucket called test will collide.
Why the destroy order matters
I wrote a stand-in to check the defer idea. A fake terraform shell script treats a file as the “infrastructure”, and a small Python harness does apply, read output, assert, and destroy in a finally. It is not Terratest, and the fake CLI is mine. I ran one test with a correct expectation and one with a wrong one:
test expecting prefix bucket-
init ok
apply: created bucket-9864
assertion passed
destroy: removed | leftover: False
test expecting prefix logs-
init ok
apply: created bucket-21779
destroy: removed | leftover: False
FAILED: output 'bucket-21779' does not start with 'logs-'
The failing test still destroyed what it made, and that is what defer gives you in Go. The failure that defer cannot cover is the one where the process is killed, for example a CI timeout, because deferred functions do not run. That is how leftover resources happen in practice, and why teams run a periodic janitor job that deletes resources tagged as test fixtures.
A versioning detail you will trip over
Terratest changed a lot in 2026. The GitHub releases page shows v1.0.0 on 11 May 2026, v1.0.1 on 27 June, and modules/core/v2.0.0 on 23 September 2026, as the latest. The README says that since v1.0.0 it follows semantic versioning, that v1 renamed symbols while keeping the old names as deprecated, that removals happen in v2, and that v2 ships under /v2 module paths. It requires Go 1.26. The v1.0.1 example above uses ...Context function names that take a t.Context(). Older tutorials, including videos from before 2026, call plain terraform.InitAndApply(t, opts). Those names are marked as deprecated, not removed, in v1, per the README. I did not check whether they survive in v2, so before copying code from a video, check the migration guides the README links.
When to choose which
| Need | Tool |
|---|---|
| Logic, naming, conditionals, validation errors | terraform test with mocks |
| Provider accepts it, outputs look right | terraform test with apply in a sandbox |
| Call the deployed thing, SSH, retries, custom cloud API checks | Terratest |
| Same tests for Terraform and OpenTofu | Terratest can point at either binary through an option, which I did not verify here |
Integration tests need a throwaway cloud account with budget alerts, and test code that is as carefully reviewed as production code.
About the video
The embed is Grow with Anto’s “Advanced Terraform Tutorial 3/4: Test IaC with Terratest”, 8 minutes 33 seconds, February 2022. It is the third episode of a series, and its chapters are intro, code, “Test terraform with terratest” (1:26), a Dockerfile for the tests, building the image, running the test and conclusions. I took that from the chapter list and did not watch it all. It is from 2022, so it predates Terratest v1 and v2 and its function names will differ from the example above. It also builds on earlier episodes of the series. English was judged from the title, description, channel and its English auto-caption track. CloudOps Champion’s 2025 video in deeper is a longer local setup walkthrough.
Where this fits
Tests prove the code does what you meant. They do not prove what you meant is allowed. Policy as code checks the plan against rules.
Check yourself
Why is the destroy deferred before the apply is written?
defer runs when the test function returns, pass or fail, so the resources get destroyed even after a failed assertion.
What kind of failure still leaves resources behind?
A killed process, such as a CI timeout, because deferred functions do not run. A scheduled cleanup of tagged test resources covers it.
When is terraform test enough and when do you add Terratest?
terraform test covers plan and apply checks expressible in HCL. Add Terratest for SSH, retries over HTTP, or checks that need Go code or cloud SDK calls.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.