Your first Terraform test

InitAndApply, then assert.

Advanced12 min · lesson 2 of 12

A Terratest test is a normal Go test function that uses the terraform module. You point it at a Terraform directory via Options, call InitAndApply to deploy, read outputs, assert on them, and destroy at the end. The minimal shape is short and readable even if you are not fluent in Go — it is mostly “apply this, check that.”

vpc_test.go
package test
import (
"testing"
"github.com/gruntwork-io/terratest/modules/terraform"
"github.com/stretchr/testify/assert"
)
func TestVpcModule(t *testing.T) {
opts := &terraform.Options{ TerraformDir: "../examples/vpc" }
defer terraform.Destroy(t, opts) // always clean up
terraform.InitAndApply(t, opts) // deploy
vpcId := terraform.Output(t, opts, "vpc_id")
assert.NotEmpty(t, vpcId) // assert on the real output
}

Options, variables, and outputs

Options carries everything about the run: the directory, input Vars (to test the module with different inputs), EnvVars, and backend config. terraform.Output reads a single output; OutputMap and OutputList read structured ones. You assert with a normal Go assertion library (testify). Run it with go test, and it will really apply your Terraform against whatever cloud your credentials point at — so run it against a sandbox.

terminal
$ cd test && go test -v -timeout 30m -run TestVpcModule
=== RUN TestVpcModule
... terraform apply ...
... assertions ...
... terraform destroy ...
--- PASS: TestVpcModule (214.3s)
Set a long timeout — real deploys are slow
Go’s default test timeout (10 minutes) is often too short for real infrastructure that takes many minutes to create and destroy, and a timeout can kill the test mid-run before destroy executes, leaking resources. Always pass a generous -timeout (e.g. 30m+) sized to your slowest deploy-plus-teardown, so the test has room to finish and clean up.