I am using terrates to test my terraform code. My code have 2 modules so I managed to configure terratest to use target option while configuring the terraformOptions and it creates both modules.
However, when it comes to clean everything, it cleans only the last module using Defer. Here is my code.
package test
import (
"fmt"
"os"
"testing"
"github.com/gruntwork-io/terratest/modules/terraform"
test_structure "github.com/gruntwork-io/terratest/modules/test-structure"
)
func configureTerraformOptions(t *testing.T, terraformDir string, tfModule string) (*terraform.Options) {
awsRegion := os.Getenv("AWS_REGION")
terraformOptions := &terraform.Options{
TerraformDir: terraformDir,
Targets: []string{tfModule},
Vars: map[string]interface{}{
"aws_region": awsRegion,
},
}
return terraformOptions
}
func TestInfra(t *testing.T) {
t.Parallel()
terraformDir := test_structure.CopyTerraformFolderToTemp(t, "../", "tests/terraform")
defer test_structure.RunTestStage(t, "destroy", func() {
terraformOptions := test_structure.LoadTerraformOptions(t, terraformDir)
terraform.Destroy(t, terraformOptions)
})
test_structure.RunTestStage(t, "setup", func() {
terraformOptionsInfra := configureTerraformOptions(t, terraformDir, "module.one")
terraformOptionsConf := configureTerraformOptions(t, terraformDir, "module.two")
test_structure.SaveTerraformOptions(t, terraformDir, terraformOptionsInfra)
test_structure.SaveTerraformOptions(t, terraformDir, terraformOptionsConf)
terraform.InitAndApply(t, terraformOptionsInfra)
terraform.InitAndApply(t, terraformOptionsConf)
})
test_structure.RunTestStage(t, "validate", func() {
terraformOptions := test_structure.LoadTerraformOptions(t, terraformDir)
testHello(t, terraformOptions)
})
}
func testHello(t *testing.T, terraformOptions *terraform.Options) {
fmt.Printf("Hello")
}
Is there any way to target like when I apply ?
Thanks;
I think there are a couple issues here:
setupstep, you're callingSaveTerraformOptionstwice, but what you have to realize is that the second call is overwriting the first one!destroystep, you callLoadTerraformOptionsandDestroyjust once, so even if you had bothterraform.Optionsstructs, you'd still only be runningdestroyon one of them.I think to fix this, in the
setupstep, you'll to call SaveTestData directly (SaveTerraformOptionsis just a wrapper for this method) with different paths:And then you'll want two
destroysteps (e.g.,destroy_infra,destroy_conf), and each should use LoadTestData to get your data back and runDestroyon it: