terraform.Destroy is a Terratest helper that removes Terraform-managed resources after an infrastructure test. Deferring the call keeps cleanup attached to the test, including when the test fails. section 9.3.2
Use terraform.Destroy as part of the standard Terratest lifecycle:
- Create a terraform.Options object with the Terraform directory, input variables, and selected Terraform or OpenTofu binary. section 9.3.2
- Defer terraform.Destroy immediately so resources are removed when the test completes or fails. section 9.3.2
- Initialize and apply the configuration, then validate outputs or the launched environment. section 9.3.2
Cleanup around a simple module test
A test for a module containing a terraform_data resource and an output can configure terraform.Options, defer terraform.Destroy, call terraform.InitAndApply, and verify that the output matches the supplied input. The deferred cleanup removes the test resources after validation. section 9.3.2
Listing 9.10 Basic structure of a Terratest test
package tests
import ( #1
"os"
"testing" #2
"github.com/gruntwork-io/terratest/modules/terraform" #3
"github.com/stretchr/testify/assert"
)
func TestExample(t *testing.T) {
t.Parallel() #4
testInput := "test" #5
terraformBinary := os.Getenv("TERRATEST_BINARY") #6
if len(terraformBinary) <= 0 {
terraformBinary = "terraform" #7
}
terraformOptions := terraform.WithDefaultRetryableErrors(t,
&terraform.Options{
TerraformDir: "../",
TerraformBinary: terraformBinary, #8
Vars: map[string]interface{}{
"test_input": testInput, #9
},
})
defer terraform.Destroy(t, terraformOptions) #10
terraform.InitAndApply(t, terraformOptions) #11
testOutput := terraform.Output(t, terraformOptions, "test_output") #12
assert.Equal(t, testInput, testOutput) #13
}
#1 We import our packages.
#2 This is the same testing package as before.
#3 Now we also pull in Terratest.
#4 This allows multiple tests to run at the same time.
#5 This is what we’ll pass to the input and will expect from the output.
#6 We use this to switch between Terraform and OpenTofu.
#7 If the environment variable is not set, we default to Terraform.
#8 We use the binary we set above.
#9 We pass the test input to the Terraform module.
#10 We defer the destroy to ensure the resources are cleaned up after tests are run.
#11 We run the Terraform init and apply.
#12 We get the output from the Terraform module.
#13 Finally, we test that the output is equal to the input.
Use the basic Terratest test structure to place terraform.Destroy alongside options setup, initialization, application, and assertions. section 9.3.2
