From e3fde1b2a25cc5b325e1950a3fcff51630a9000c Mon Sep 17 00:00:00 2001 From: Modular Magician Date: Tue, 17 Mar 2020 22:56:41 +0000 Subject: [PATCH] Ansible - Regional SSL Certs + Health Check (#3210) * done * first try! * copyright * changing examples * removing google provider * test fixes Signed-off-by: Modular Magician --- .changelog/3210.txt | 3 + google/provider.go | 5 +- ...resource_compute_region_ssl_certificate.go | 373 ++++++++++++++++++ ...e_region_ssl_certificate_generated_test.go | 146 +++++++ ...ute_region_ssl_certificate_sweeper_test.go | 119 ++++++ ...mpute_region_ssl_certificate.html.markdown | 260 ++++++++++++ 6 files changed, 904 insertions(+), 2 deletions(-) create mode 100644 .changelog/3210.txt create mode 100644 google/resource_compute_region_ssl_certificate.go create mode 100644 google/resource_compute_region_ssl_certificate_generated_test.go create mode 100644 google/resource_compute_region_ssl_certificate_sweeper_test.go create mode 100644 website/docs/r/compute_region_ssl_certificate.html.markdown diff --git a/.changelog/3210.txt b/.changelog/3210.txt new file mode 100644 index 00000000000..1313867a5a5 --- /dev/null +++ b/.changelog/3210.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +`google_compute_region_ssl_certificate` +``` diff --git a/google/provider.go b/google/provider.go index 42f457a016d..474f3a28a67 100644 --- a/google/provider.go +++ b/google/provider.go @@ -512,9 +512,9 @@ func Provider() terraform.ResourceProvider { return provider } -// Generated resources: 108 +// Generated resources: 109 // Generated IAM resources: 51 -// Total generated resources: 159 +// Total generated resources: 160 func ResourceMap() map[string]*schema.Resource { resourceMap, _ := ResourceMapWithErrors() return resourceMap @@ -590,6 +590,7 @@ func ResourceMapWithErrors() (map[string]*schema.Resource, error) { "google_compute_router_peer": resourceComputeRouterBgpPeer(), "google_compute_snapshot": resourceComputeSnapshot(), "google_compute_ssl_certificate": resourceComputeSslCertificate(), + "google_compute_region_ssl_certificate": resourceComputeRegionSslCertificate(), "google_compute_reservation": resourceComputeReservation(), "google_compute_ssl_policy": resourceComputeSslPolicy(), "google_compute_subnetwork": resourceComputeSubnetwork(), diff --git a/google/resource_compute_region_ssl_certificate.go b/google/resource_compute_region_ssl_certificate.go new file mode 100644 index 00000000000..9e05cc81159 --- /dev/null +++ b/google/resource_compute_region_ssl_certificate.go @@ -0,0 +1,373 @@ +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** +// +// ---------------------------------------------------------------------------- +// +// This file is automatically generated by Magic Modules and manual +// changes will be clobbered when the file is regenerated. +// +// Please read more about how to change this file in +// .github/CONTRIBUTING.md. +// +// ---------------------------------------------------------------------------- + +package google + +import ( + "fmt" + "log" + "reflect" + "strconv" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func resourceComputeRegionSslCertificate() *schema.Resource { + return &schema.Resource{ + Create: resourceComputeRegionSslCertificateCreate, + Read: resourceComputeRegionSslCertificateRead, + Delete: resourceComputeRegionSslCertificateDelete, + + Importer: &schema.ResourceImporter{ + State: resourceComputeRegionSslCertificateImport, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(4 * time.Minute), + Delete: schema.DefaultTimeout(4 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "certificate": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `The certificate in PEM format. +The certificate chain must be no greater than 5 certs long. +The chain must include at least one intermediate cert.`, + Sensitive: true, + }, + "private_key": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + DiffSuppressFunc: sha256DiffSuppress, + Description: `The write-only private key in PEM format.`, + Sensitive: true, + }, + "description": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Description: `An optional description of this resource.`, + }, + "name": { + Type: schema.TypeString, + Computed: true, + Optional: true, + ForceNew: true, + ValidateFunc: validateGCPName, + Description: `Name of the resource. Provided by the client when the resource is +created. The name must be 1-63 characters long, and comply with +RFC1035. Specifically, the name must be 1-63 characters long and match +the regular expression '[a-z]([-a-z0-9]*[a-z0-9])?' which means the +first character must be a lowercase letter, and all following +characters must be a dash, lowercase letter, or digit, except the last +character, which cannot be a dash. + + +These are in the same namespace as the managed SSL certificates.`, + }, + "region": { + Type: schema.TypeString, + Computed: true, + Optional: true, + ForceNew: true, + DiffSuppressFunc: compareSelfLinkOrResourceName, + Description: `The Region in which the created regional ssl certificate should reside. +If it is not provided, the provider region is used.`, + }, + "certificate_id": { + Type: schema.TypeInt, + Computed: true, + Description: `The unique identifier for the resource.`, + }, + "creation_timestamp": { + Type: schema.TypeString, + Computed: true, + Description: `Creation timestamp in RFC3339 text format.`, + }, + "name_prefix": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + ConflictsWith: []string{"name"}, + ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { + // https://cloud.google.com/compute/docs/reference/latest/sslCertificates#resource + // uuid is 26 characters, limit the prefix to 37. + value := v.(string) + if len(value) > 37 { + errors = append(errors, fmt.Errorf( + "%q cannot be longer than 37 characters, name is limited to 63", k)) + } + return + }, + }, + "project": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, + "self_link": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourceComputeRegionSslCertificateCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + obj := make(map[string]interface{}) + certificateProp, err := expandComputeRegionSslCertificateCertificate(d.Get("certificate"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("certificate"); !isEmptyValue(reflect.ValueOf(certificateProp)) && (ok || !reflect.DeepEqual(v, certificateProp)) { + obj["certificate"] = certificateProp + } + descriptionProp, err := expandComputeRegionSslCertificateDescription(d.Get("description"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("description"); !isEmptyValue(reflect.ValueOf(descriptionProp)) && (ok || !reflect.DeepEqual(v, descriptionProp)) { + obj["description"] = descriptionProp + } + nameProp, err := expandComputeRegionSslCertificateName(d.Get("name"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("name"); !isEmptyValue(reflect.ValueOf(nameProp)) && (ok || !reflect.DeepEqual(v, nameProp)) { + obj["name"] = nameProp + } + privateKeyProp, err := expandComputeRegionSslCertificatePrivateKey(d.Get("private_key"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("private_key"); !isEmptyValue(reflect.ValueOf(privateKeyProp)) && (ok || !reflect.DeepEqual(v, privateKeyProp)) { + obj["privateKey"] = privateKeyProp + } + regionProp, err := expandComputeRegionSslCertificateRegion(d.Get("region"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("region"); !isEmptyValue(reflect.ValueOf(regionProp)) && (ok || !reflect.DeepEqual(v, regionProp)) { + obj["region"] = regionProp + } + + url, err := replaceVars(d, config, "{{ComputeBasePath}}projects/{{project}}/regions/{{region}}/sslCertificates") + if err != nil { + return err + } + + log.Printf("[DEBUG] Creating new RegionSslCertificate: %#v", obj) + project, err := getProject(d, config) + if err != nil { + return err + } + res, err := sendRequestWithTimeout(config, "POST", project, url, obj, d.Timeout(schema.TimeoutCreate)) + if err != nil { + return fmt.Errorf("Error creating RegionSslCertificate: %s", err) + } + + // Store the ID now + id, err := replaceVars(d, config, "projects/{{project}}/regions/{{region}}/sslCertificates/{{name}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + err = computeOperationWaitTime( + config, res, project, "Creating RegionSslCertificate", + int(d.Timeout(schema.TimeoutCreate).Minutes())) + + if err != nil { + // The resource didn't actually create + d.SetId("") + return fmt.Errorf("Error waiting to create RegionSslCertificate: %s", err) + } + + log.Printf("[DEBUG] Finished creating RegionSslCertificate %q: %#v", d.Id(), res) + + return resourceComputeRegionSslCertificateRead(d, meta) +} + +func resourceComputeRegionSslCertificateRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + url, err := replaceVars(d, config, "{{ComputeBasePath}}projects/{{project}}/regions/{{region}}/sslCertificates/{{name}}") + if err != nil { + return err + } + + project, err := getProject(d, config) + if err != nil { + return err + } + res, err := sendRequest(config, "GET", project, url, nil) + if err != nil { + return handleNotFoundError(err, d, fmt.Sprintf("ComputeRegionSslCertificate %q", d.Id())) + } + + if err := d.Set("project", project); err != nil { + return fmt.Errorf("Error reading RegionSslCertificate: %s", err) + } + + if err := d.Set("certificate", flattenComputeRegionSslCertificateCertificate(res["certificate"], d, config)); err != nil { + return fmt.Errorf("Error reading RegionSslCertificate: %s", err) + } + if err := d.Set("creation_timestamp", flattenComputeRegionSslCertificateCreationTimestamp(res["creationTimestamp"], d, config)); err != nil { + return fmt.Errorf("Error reading RegionSslCertificate: %s", err) + } + if err := d.Set("description", flattenComputeRegionSslCertificateDescription(res["description"], d, config)); err != nil { + return fmt.Errorf("Error reading RegionSslCertificate: %s", err) + } + if err := d.Set("certificate_id", flattenComputeRegionSslCertificateCertificateId(res["id"], d, config)); err != nil { + return fmt.Errorf("Error reading RegionSslCertificate: %s", err) + } + if err := d.Set("name", flattenComputeRegionSslCertificateName(res["name"], d, config)); err != nil { + return fmt.Errorf("Error reading RegionSslCertificate: %s", err) + } + if err := d.Set("region", flattenComputeRegionSslCertificateRegion(res["region"], d, config)); err != nil { + return fmt.Errorf("Error reading RegionSslCertificate: %s", err) + } + if err := d.Set("self_link", ConvertSelfLinkToV1(res["selfLink"].(string))); err != nil { + return fmt.Errorf("Error reading RegionSslCertificate: %s", err) + } + + return nil +} + +func resourceComputeRegionSslCertificateDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + project, err := getProject(d, config) + if err != nil { + return err + } + + url, err := replaceVars(d, config, "{{ComputeBasePath}}projects/{{project}}/regions/{{region}}/sslCertificates/{{name}}") + if err != nil { + return err + } + + var obj map[string]interface{} + log.Printf("[DEBUG] Deleting RegionSslCertificate %q", d.Id()) + + res, err := sendRequestWithTimeout(config, "DELETE", project, url, obj, d.Timeout(schema.TimeoutDelete)) + if err != nil { + return handleNotFoundError(err, d, "RegionSslCertificate") + } + + err = computeOperationWaitTime( + config, res, project, "Deleting RegionSslCertificate", + int(d.Timeout(schema.TimeoutDelete).Minutes())) + + if err != nil { + return err + } + + log.Printf("[DEBUG] Finished deleting RegionSslCertificate %q: %#v", d.Id(), res) + return nil +} + +func resourceComputeRegionSslCertificateImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + config := meta.(*Config) + if err := parseImportId([]string{ + "projects/(?P[^/]+)/regions/(?P[^/]+)/sslCertificates/(?P[^/]+)", + "(?P[^/]+)/(?P[^/]+)/(?P[^/]+)", + "(?P[^/]+)/(?P[^/]+)", + "(?P[^/]+)", + }, d, config); err != nil { + return nil, err + } + + // Replace import id for the resource id + id, err := replaceVars(d, config, "projects/{{project}}/regions/{{region}}/sslCertificates/{{name}}") + if err != nil { + return nil, fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + return []*schema.ResourceData{d}, nil +} + +func flattenComputeRegionSslCertificateCertificate(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenComputeRegionSslCertificateCreationTimestamp(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenComputeRegionSslCertificateDescription(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenComputeRegionSslCertificateCertificateId(v interface{}, d *schema.ResourceData, config *Config) interface{} { + // Handles the string fixed64 format + if strVal, ok := v.(string); ok { + if intVal, err := strconv.ParseInt(strVal, 10, 64); err == nil { + return intVal + } // let terraform core handle it if we can't convert the string to an int. + } + return v +} + +func flattenComputeRegionSslCertificateName(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenComputeRegionSslCertificateRegion(v interface{}, d *schema.ResourceData, config *Config) interface{} { + if v == nil { + return v + } + return NameFromSelfLinkStateFunc(v) +} + +func expandComputeRegionSslCertificateCertificate(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func expandComputeRegionSslCertificateDescription(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func expandComputeRegionSslCertificateName(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + var certName string + if v, ok := d.GetOk("name"); ok { + certName = v.(string) + } else if v, ok := d.GetOk("name_prefix"); ok { + certName = resource.PrefixedUniqueId(v.(string)) + } else { + certName = resource.UniqueId() + } + + // We need to get the {{name}} into schema to set the ID using ReplaceVars + d.Set("name", certName) + + return certName, nil +} + +func expandComputeRegionSslCertificatePrivateKey(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func expandComputeRegionSslCertificateRegion(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + f, err := parseGlobalFieldValue("regions", v.(string), "project", d, config, true) + if err != nil { + return nil, fmt.Errorf("Invalid value for region: %s", err) + } + return f.RelativeLink(), nil +} diff --git a/google/resource_compute_region_ssl_certificate_generated_test.go b/google/resource_compute_region_ssl_certificate_generated_test.go new file mode 100644 index 00000000000..74413c7233e --- /dev/null +++ b/google/resource_compute_region_ssl_certificate_generated_test.go @@ -0,0 +1,146 @@ +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** +// +// ---------------------------------------------------------------------------- +// +// This file is automatically generated by Magic Modules and manual +// changes will be clobbered when the file is regenerated. +// +// Please read more about how to change this file in +// .github/CONTRIBUTING.md. +// +// ---------------------------------------------------------------------------- + +package google + +import ( + "fmt" + "strings" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/terraform" +) + +func TestAccComputeRegionSslCertificate_regionSslCertificateBasicExample(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": acctest.RandString(10), + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckComputeRegionSslCertificateDestroy, + Steps: []resource.TestStep{ + { + Config: testAccComputeRegionSslCertificate_regionSslCertificateBasicExample(context), + }, + { + ResourceName: "google_compute_region_ssl_certificate.default", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"private_key", "name_prefix"}, + }, + }, + }) +} + +func testAccComputeRegionSslCertificate_regionSslCertificateBasicExample(context map[string]interface{}) string { + return Nprintf(` +resource "google_compute_region_ssl_certificate" "default" { + region = "us-central1" + name_prefix = "my-certificate-" + description = "a description" + private_key = file("test-fixtures/ssl_cert/test.key") + certificate = file("test-fixtures/ssl_cert/test.crt") + + lifecycle { + create_before_destroy = true + } +} +`, context) +} + +func TestAccComputeRegionSslCertificate_regionSslCertificateRandomProviderExample(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": acctest.RandString(10), + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckComputeRegionSslCertificateDestroy, + Steps: []resource.TestStep{ + { + Config: testAccComputeRegionSslCertificate_regionSslCertificateRandomProviderExample(context), + }, + { + ResourceName: "google_compute_region_ssl_certificate.default", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"private_key"}, + }, + }, + }) +} + +func testAccComputeRegionSslCertificate_regionSslCertificateRandomProviderExample(context map[string]interface{}) string { + return Nprintf(` +# You may also want to control name generation explicitly: +resource "google_compute_region_ssl_certificate" "default" { + region = "us-central1" + + # The name will contain 8 random hex digits, + # e.g. "my-certificate-48ab27cd2a" + name = random_id.certificate.hex + private_key = file("test-fixtures/ssl_cert/test.key") + certificate = file("test-fixtures/ssl_cert/test.crt") + + lifecycle { + create_before_destroy = true + } +} + +resource "random_id" "certificate" { + byte_length = 4 + prefix = "my-certificate-" + + # For security, do not expose raw certificate values in the output + keepers = { + private_key = filebase64sha256("test-fixtures/ssl_cert/test.key") + certificate = filebase64sha256("test-fixtures/ssl_cert/test.crt") + } +} +`, context) +} + +func testAccCheckComputeRegionSslCertificateDestroy(s *terraform.State) error { + for name, rs := range s.RootModule().Resources { + if rs.Type != "google_compute_region_ssl_certificate" { + continue + } + if strings.HasPrefix(name, "data.") { + continue + } + + config := testAccProvider.Meta().(*Config) + + url, err := replaceVarsForTest(config, rs, "{{ComputeBasePath}}projects/{{project}}/regions/{{region}}/sslCertificates/{{name}}") + if err != nil { + return err + } + + _, err = sendRequest(config, "GET", "", url, nil) + if err == nil { + return fmt.Errorf("ComputeRegionSslCertificate still exists at %s", url) + } + } + + return nil +} diff --git a/google/resource_compute_region_ssl_certificate_sweeper_test.go b/google/resource_compute_region_ssl_certificate_sweeper_test.go new file mode 100644 index 00000000000..f02cd0eea9c --- /dev/null +++ b/google/resource_compute_region_ssl_certificate_sweeper_test.go @@ -0,0 +1,119 @@ +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** +// +// ---------------------------------------------------------------------------- +// +// This file is automatically generated by Magic Modules and manual +// changes will be clobbered when the file is regenerated. +// +// Please read more about how to change this file in +// .github/CONTRIBUTING.md. +// +// ---------------------------------------------------------------------------- + +package google + +import ( + "context" + "log" + "strings" + + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" +) + +func init() { + resource.AddTestSweepers("ComputeRegionSslCertificate", &resource.Sweeper{ + Name: "ComputeRegionSslCertificate", + F: testSweepComputeRegionSslCertificate, + }) +} + +// At the time of writing, the CI only passes us-central1 as the region +func testSweepComputeRegionSslCertificate(region string) error { + resourceName := "ComputeRegionSslCertificate" + log.Printf("[INFO][SWEEPER_LOG] Starting sweeper for %s", resourceName) + + config, err := sharedConfigForRegion(region) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] error getting shared config for region: %s", err) + return err + } + + err = config.LoadAndValidate(context.Background()) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] error loading: %s", err) + return err + } + + // Setup variables to replace in list template + d := &ResourceDataMock{ + FieldsInSchema: map[string]interface{}{ + "project": config.Project, + "region": region, + "location": region, + "zone": "-", + }, + } + + listTemplate := strings.Split("https://www.googleapis.com/compute/v1/projects/{{project}}/regions/{{region}}/sslCertificates", "?")[0] + listUrl, err := replaceVars(d, config, listTemplate) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] error preparing sweeper list url: %s", err) + return nil + } + + res, err := sendRequest(config, "GET", config.Project, listUrl, nil) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] Error in response from request %s: %s", listUrl, err) + return nil + } + + resourceList, ok := res["items"] + if !ok { + log.Printf("[INFO][SWEEPER_LOG] Nothing found in response.") + return nil + } + + rl := resourceList.([]interface{}) + + log.Printf("[INFO][SWEEPER_LOG] Found %d items in %s list response.", len(rl), resourceName) + // items who don't match the tf-test prefix + nonPrefixCount := 0 + for _, ri := range rl { + obj := ri.(map[string]interface{}) + if obj["name"] == nil { + log.Printf("[INFO][SWEEPER_LOG] %s resource name was nil", resourceName) + return nil + } + + name := GetResourceNameFromSelfLink(obj["name"].(string)) + // Only sweep resources with the test prefix + if !strings.HasPrefix(name, "tf-test") { + nonPrefixCount++ + continue + } + + deleteTemplate := "https://www.googleapis.com/compute/v1/projects/{{project}}/regions/{{region}}/sslCertificates/{{name}}" + deleteUrl, err := replaceVars(d, config, deleteTemplate) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] error preparing delete url: %s", err) + return nil + } + deleteUrl = deleteUrl + name + + // Don't wait on operations as we may have a lot to delete + _, err = sendRequest(config, "DELETE", config.Project, deleteUrl, nil) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] Error deleting for url %s : %s", deleteUrl, err) + } else { + log.Printf("[INFO][SWEEPER_LOG] Sent delete request for %s resource: %s", resourceName, name) + } + } + + if nonPrefixCount > 0 { + log.Printf("[INFO][SWEEPER_LOG] %d items without tf_test prefix remain.", nonPrefixCount) + } + + return nil +} diff --git a/website/docs/r/compute_region_ssl_certificate.html.markdown b/website/docs/r/compute_region_ssl_certificate.html.markdown new file mode 100644 index 00000000000..5e9a29668ed --- /dev/null +++ b/website/docs/r/compute_region_ssl_certificate.html.markdown @@ -0,0 +1,260 @@ +--- +# ---------------------------------------------------------------------------- +# +# *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** +# +# ---------------------------------------------------------------------------- +# +# This file is automatically generated by Magic Modules and manual +# changes will be clobbered when the file is regenerated. +# +# Please read more about how to change this file in +# .github/CONTRIBUTING.md. +# +# ---------------------------------------------------------------------------- +subcategory: "Compute Engine" +layout: "google" +page_title: "Google: google_compute_region_ssl_certificate" +sidebar_current: "docs-google-compute-region-ssl-certificate" +description: |- + A RegionSslCertificate resource, used for HTTPS load balancing. +--- + +# google\_compute\_region\_ssl\_certificate + +A RegionSslCertificate resource, used for HTTPS load balancing. This resource +provides a mechanism to upload an SSL key and certificate to +the load balancer to serve secure connections from the user. + + +To get more information about RegionSslCertificate, see: + +* [API documentation](https://cloud.google.com/compute/docs/reference/rest/v1/regionSslCertificates) +* How-to Guides + * [Official Documentation](https://cloud.google.com/load-balancing/docs/ssl-certificates) + + +## Example Usage - Region Ssl Certificate Basic + + +```hcl +resource "google_compute_region_ssl_certificate" "default" { + region = "us-central1" + name_prefix = "my-certificate-" + description = "a description" + private_key = file("path/to/private.key") + certificate = file("path/to/certificate.crt") + + lifecycle { + create_before_destroy = true + } +} +``` + +## Example Usage - Region Ssl Certificate Random Provider + + +```hcl +# You may also want to control name generation explicitly: +resource "google_compute_region_ssl_certificate" "default" { + region = "us-central1" + + # The name will contain 8 random hex digits, + # e.g. "my-certificate-48ab27cd2a" + name = random_id.certificate.hex + private_key = file("path/to/private.key") + certificate = file("path/to/certificate.crt") + + lifecycle { + create_before_destroy = true + } +} + +resource "random_id" "certificate" { + byte_length = 4 + prefix = "my-certificate-" + + # For security, do not expose raw certificate values in the output + keepers = { + private_key = filebase64sha256("path/to/private.key") + certificate = filebase64sha256("path/to/certificate.crt") + } +} +``` + +## Example Usage - Region Ssl Certificate Target Https Proxies + + +```hcl +// Using with Region Target HTTPS Proxies +// +// SSL certificates cannot be updated after creation. In order to apply +// the specified configuration, Terraform will destroy the existing +// resource and create a replacement. To effectively use an SSL +// certificate resource with a Target HTTPS Proxy resource, it's +// recommended to specify create_before_destroy in a lifecycle block. +// Either omit the Instance Template name attribute, specify a partial +// name with name_prefix, or use random_id resource. Example: + +resource "google_compute_region_ssl_certificate" "default" { + provider = google-beta + region = "us-central1" + name_prefix = "my-certificate-" + private_key = file("path/to/private.key") + certificate = file("path/to/certificate.crt") + + lifecycle { + create_before_destroy = true + } +} + +resource "google_compute_region_target_https_proxy" "default" { + provider = google-beta + region = "us-central1" + name = "test-proxy" + url_map = google_compute_region_url_map.default.self_link + ssl_certificates = [google_compute_region_ssl_certificate.default.self_link] +} + +resource "google_compute_region_url_map" "default" { + provider = google-beta + region = "us-central1" + name = "url-map" + description = "a description" + + default_service = google_compute_region_backend_service.default.self_link + + host_rule { + hosts = ["mysite.com"] + path_matcher = "allpaths" + } + + path_matcher { + name = "allpaths" + default_service = google_compute_region_backend_service.default.self_link + + path_rule { + paths = ["/*"] + service = google_compute_region_backend_service.default.self_link + } + } +} + +resource "google_compute_region_backend_service" "default" { + provider = google-beta + region = "us-central1" + name = "backend-service" + protocol = "HTTP" + timeout_sec = 10 + + health_checks = [google_compute_region_health_check.default.self_link] +} + +resource "google_compute_region_health_check" "default" { + provider = google-beta + region = "us-central1" + name = "http-health-check" + http_health_check { + port = 80 + } +} +``` + +## Argument Reference + +The following arguments are supported: + + +* `certificate` - + (Required) + The certificate in PEM format. + The certificate chain must be no greater than 5 certs long. + The chain must include at least one intermediate cert. + +* `private_key` - + (Required) + The write-only private key in PEM format. + + +- - - + + +* `description` - + (Optional) + An optional description of this resource. + +* `name` - + (Optional) + Name of the resource. Provided by the client when the resource is + created. The name must be 1-63 characters long, and comply with + RFC1035. Specifically, the name must be 1-63 characters long and match + the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the + first character must be a lowercase letter, and all following + characters must be a dash, lowercase letter, or digit, except the last + character, which cannot be a dash. + + These are in the same namespace as the managed SSL certificates. + +* `region` - + (Optional) + The Region in which the created regional ssl certificate should reside. + If it is not provided, the provider region is used. + +* `project` - (Optional) The ID of the project in which the resource belongs. + If it is not provided, the provider project is used. + + +* `name_prefix` - (Optional) Creates a unique name beginning with the + specified prefix. Conflicts with `name`. + +## Attributes Reference + +In addition to the arguments listed above, the following computed attributes are exported: + +* `id` - an identifier for the resource with format `projects/{{project}}/regions/{{region}}/sslCertificates/{{name}}` + +* `creation_timestamp` - + Creation timestamp in RFC3339 text format. + +* `certificate_id` - + The unique identifier for the resource. +* `self_link` - The URI of the created resource. + + +## Timeouts + +This resource provides the following +[Timeouts](/docs/configuration/resources.html#timeouts) configuration options: + +- `create` - Default is 4 minutes. +- `delete` - Default is 4 minutes. + +## Import + +RegionSslCertificate can be imported using any of these accepted formats: + +``` +$ terraform import google_compute_region_ssl_certificate.default projects/{{project}}/regions/{{region}}/sslCertificates/{{name}} +$ terraform import google_compute_region_ssl_certificate.default {{project}}/{{region}}/{{name}} +$ terraform import google_compute_region_ssl_certificate.default {{region}}/{{name}} +$ terraform import google_compute_region_ssl_certificate.default {{name}} +``` + +-> If you're importing a resource with beta features, make sure to include `-provider=google-beta` +as an argument so that Terraform uses the correct provider to import your resource. + +## User Project Overrides + +This resource supports [User Project Overrides](https://www.terraform.io/docs/providers/google/guides/provider_reference.html#user_project_override).