github.com/darmach/terratest@v0.34.8-0.20210517103231-80931f95e3ff/test/terraform_aws_network_example_test.go (about) 1 package test 2 3 import ( 4 "testing" 5 6 "github.com/gruntwork-io/terratest/modules/aws" 7 "github.com/gruntwork-io/terratest/modules/terraform" 8 "github.com/stretchr/testify/assert" 9 "github.com/stretchr/testify/require" 10 ) 11 12 // An example of how to test the Terraform module in examples/terraform-aws-network-example using Terratest. 13 func TestTerraformAwsNetworkExample(t *testing.T) { 14 t.Parallel() 15 16 // Pick a random AWS region to test in. This helps ensure your code works in all regions. 17 awsRegion := aws.GetRandomStableRegion(t, nil, nil) 18 19 // Give the VPC and the subnets correct CIDRs 20 vpcCidr := "10.10.0.0/16" 21 privateSubnetCidr := "10.10.1.0/24" 22 publicSubnetCidr := "10.10.2.0/24" 23 24 // Construct the terraform options with default retryable errors to handle the most common retryable errors in 25 // terraform testing. 26 terraformOptions := terraform.WithDefaultRetryableErrors(t, &terraform.Options{ 27 // The path to where our Terraform code is located 28 TerraformDir: "../examples/terraform-aws-network-example", 29 30 // Variables to pass to our Terraform code using -var options 31 Vars: map[string]interface{}{ 32 "main_vpc_cidr": vpcCidr, 33 "private_subnet_cidr": privateSubnetCidr, 34 "public_subnet_cidr": publicSubnetCidr, 35 "aws_region": awsRegion, 36 }, 37 }) 38 39 // At the end of the test, run `terraform destroy` to clean up any resources that were created 40 defer terraform.Destroy(t, terraformOptions) 41 42 // This will run `terraform init` and `terraform apply` and fail the test if there are any errors 43 terraform.InitAndApply(t, terraformOptions) 44 45 // Run `terraform output` to get the value of an output variable 46 publicSubnetId := terraform.Output(t, terraformOptions, "public_subnet_id") 47 privateSubnetId := terraform.Output(t, terraformOptions, "private_subnet_id") 48 vpcId := terraform.Output(t, terraformOptions, "main_vpc_id") 49 50 subnets := aws.GetSubnetsForVpc(t, vpcId, awsRegion) 51 52 require.Equal(t, 2, len(subnets)) 53 // Verify if the network that is supposed to be public is really public 54 assert.True(t, aws.IsPublicSubnet(t, publicSubnetId, awsRegion)) 55 // Verify if the network that is supposed to be private is really private 56 assert.False(t, aws.IsPublicSubnet(t, privateSubnetId, awsRegion)) 57 }