github.com/darmach/terratest@v0.34.8-0.20210517103231-80931f95e3ff/test/gcp/terraform_gcp_hello_world_example_test.go (about)

     1  // +build gcp
     2  
     3  // NOTE: We use build tags to differentiate GCP testing for better isolation and parallelism when executing our tests.
     4  
     5  package test
     6  
     7  import (
     8  	"fmt"
     9  	"strings"
    10  	"testing"
    11  
    12  	"github.com/gruntwork-io/terratest/modules/gcp"
    13  	"github.com/gruntwork-io/terratest/modules/random"
    14  	"github.com/gruntwork-io/terratest/modules/terraform"
    15  )
    16  
    17  func TestTerraformGcpHelloWorldExample(t *testing.T) {
    18  	t.Parallel()
    19  
    20  	// website::tag::1:: Get the Project Id to use
    21  	projectId := gcp.GetGoogleProjectIDFromEnvVar(t)
    22  
    23  	// website::tag::2:: Give the example instance a unique name
    24  	instanceName := fmt.Sprintf("gcp-hello-world-example-%s", strings.ToLower(random.UniqueId()))
    25  
    26  	// website::tag::6:: Construct the terraform options with default retryable errors to handle the most common
    27  	// retryable errors in terraform testing.
    28  	terraformOptions := terraform.WithDefaultRetryableErrors(t, &terraform.Options{
    29  		// website::tag::3:: The path to where our Terraform code is located
    30  		TerraformDir: "../../examples/terraform-gcp-hello-world-example",
    31  
    32  		// website::tag::4:: Variables to pass to our Terraform code using -var options
    33  		Vars: map[string]interface{}{
    34  			"instance_name": instanceName,
    35  		},
    36  
    37  		// website::tag::5:: Variables to pass to our Terraform code using TF_VAR_xxx environment variables
    38  		EnvVars: map[string]string{
    39  			"GOOGLE_CLOUD_PROJECT": projectId,
    40  		},
    41  	})
    42  
    43  	// website::tag::8:: At the end of the test, run `terraform destroy` to clean up any resources that were created
    44  	defer terraform.Destroy(t, terraformOptions)
    45  
    46  	// website::tag::7:: Run `terraform init` and `terraform apply`. Fail the test if there are any errors.
    47  	terraform.InitAndApply(t, terraformOptions)
    48  }