github.com/darmach/terratest@v0.34.8-0.20210517103231-80931f95e3ff/test/gcp/packer_gcp_basic_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  	"testing"
     9  	"time"
    10  
    11  	"github.com/gruntwork-io/terratest/modules/gcp"
    12  	"github.com/gruntwork-io/terratest/modules/packer"
    13  )
    14  
    15  // Occasionally, a Packer build may fail due to intermittent issues (e.g., brief network outage or EC2 issue). We try
    16  // to make our tests resilient to that by specifying those known common errors here and telling our builds to retry if
    17  // they hit those errors.
    18  var DefaultRetryablePackerErrors = map[string]string{
    19  	"Script disconnected unexpectedly":                                                 "Occasionally, Packer seems to lose connectivity to AWS, perhaps due to a brief network outage",
    20  	"can not open /var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_xenial_InRelease": "Occasionally, apt-get fails on ubuntu to update the cache",
    21  }
    22  var DefaultTimeBetweenPackerRetries = 15 * time.Second
    23  
    24  const DefaultMaxPackerRetries = 3
    25  
    26  // An example of how to test the Packer template in examples/packer-basic-example using Terratest.
    27  func TestPackerGCPBasicExample(t *testing.T) {
    28  	t.Parallel()
    29  
    30  	// Get the Project Id to use
    31  	projectID := gcp.GetGoogleProjectIDFromEnvVar(t)
    32  
    33  	// Pick a random GCP zone to test in. This helps ensure your code works in all regions.
    34  	// On October 22, 2018, GCP launched the asia-east2 region, which promptly failed all our tests, so blacklist asia-east2.
    35  	zone := gcp.GetRandomZone(t, projectID, nil, nil, []string{"asia-east2"})
    36  
    37  	packerOptions := &packer.Options{
    38  		// The path to where the Packer template is located
    39  		Template: "../../examples/packer-basic-example/build.json",
    40  
    41  		// Variables to pass to our Packer build using -var options
    42  		Vars: map[string]string{
    43  			"gcp_project_id": projectID,
    44  			"gcp_zone":       zone,
    45  		},
    46  
    47  		// Only build the Google Compute Image
    48  		Only: "googlecompute",
    49  
    50  		// Configure retries for intermittent errors
    51  		RetryableErrors:    DefaultRetryablePackerErrors,
    52  		TimeBetweenRetries: DefaultTimeBetweenPackerRetries,
    53  		MaxRetries:         DefaultMaxPackerRetries,
    54  	}
    55  
    56  	// Make sure the Packer build completes successfully
    57  	imageName := packer.BuildArtifact(t, packerOptions)
    58  
    59  	// Delete the Image after we're done
    60  	image := gcp.FetchImage(t, projectID, imageName)
    61  	defer image.DeleteImage(t)
    62  }