github.com/darmach/terratest@v0.34.8-0.20210517103231-80931f95e3ff/test/terraform_backend_example_test.go (about) 1 package test 2 3 import ( 4 "fmt" 5 "strings" 6 "testing" 7 8 "github.com/gruntwork-io/terratest/modules/aws" 9 "github.com/gruntwork-io/terratest/modules/random" 10 "github.com/gruntwork-io/terratest/modules/terraform" 11 "github.com/stretchr/testify/require" 12 ) 13 14 // An example of how to test the Terraform module in examples/terraform-backend-example using Terratest. 15 func TestTerraformBackendExample(t *testing.T) { 16 t.Parallel() 17 18 awsRegion := aws.GetRandomRegion(t, nil, nil) 19 uniqueId := random.UniqueId() 20 21 // Create an S3 bucket where we can store state 22 bucketName := fmt.Sprintf("test-terraform-backend-example-%s", strings.ToLower(uniqueId)) 23 defer cleanupS3Bucket(t, awsRegion, bucketName) 24 aws.CreateS3Bucket(t, awsRegion, bucketName) 25 26 key := fmt.Sprintf("%s/terraform.tfstate", uniqueId) 27 data := fmt.Sprintf("data-for-test-%s", uniqueId) 28 29 // Deploy the module, configuring it to use the S3 bucket as an S3 backend 30 terraformOptions := terraform.WithDefaultRetryableErrors(t, &terraform.Options{ 31 TerraformDir: "../examples/terraform-backend-example", 32 Vars: map[string]interface{}{ 33 "foo": data, 34 }, 35 BackendConfig: map[string]interface{}{ 36 "bucket": bucketName, 37 "key": key, 38 "region": awsRegion, 39 }, 40 }) 41 42 defer terraform.Destroy(t, terraformOptions) 43 terraform.InitAndApply(t, terraformOptions) 44 45 // Check a state file actually got stored and contains our data in it somewhere (since that data is used in an 46 // output of the Terraform code) 47 contents := aws.GetS3ObjectContents(t, awsRegion, bucketName, key) 48 require.Contains(t, contents, data) 49 50 // The module doesn't really *do* anything, so we just check a dummy output here and move on 51 foo := terraform.OutputRequired(t, terraformOptions, "foo") 52 require.Equal(t, data, foo) 53 } 54 55 func cleanupS3Bucket(t *testing.T, awsRegion string, bucketName string) { 56 aws.EmptyS3Bucket(t, awsRegion, bucketName) 57 aws.DeleteS3Bucket(t, awsRegion, bucketName) 58 }