From 426ce72ee5898e1895927ffa712fdf010475f7dd Mon Sep 17 00:00:00 2001 From: Modular Magician Date: Wed, 11 May 2022 18:10:58 +0000 Subject: [PATCH] add certificate manager back in (#6004) Signed-off-by: Modular Magician --- .changelog/6004.txt | 6 + google/certificate_manager_operation.go | 61 ++ google/config.go | 4 + google/provider.go | 15 +- ...esource_certificate_manager_certificate.go | 594 ++++++++++++++++++ ...cate_manager_certificate_generated_test.go | 115 ++++ ...ficate_manager_certificate_sweeper_test.go | 124 ++++ ...e_certificate_manager_dns_authorization.go | 430 +++++++++++++ ...anager_dns_authorization_generated_test.go | 104 +++ ..._manager_dns_authorization_sweeper_test.go | 124 ++++ ...deploy_delivery_pipeline_generated_test.go | 8 +- ...ource_clouddeploy_target_generated_test.go | 8 +- ...tificate_manager_certificate.html.markdown | 181 ++++++ ...te_manager_dns_authorization.html.markdown | 138 ++++ website/google.erb | 20 + 15 files changed, 1922 insertions(+), 10 deletions(-) create mode 100644 .changelog/6004.txt create mode 100644 google/certificate_manager_operation.go create mode 100644 google/resource_certificate_manager_certificate.go create mode 100644 google/resource_certificate_manager_certificate_generated_test.go create mode 100644 google/resource_certificate_manager_certificate_sweeper_test.go create mode 100644 google/resource_certificate_manager_dns_authorization.go create mode 100644 google/resource_certificate_manager_dns_authorization_generated_test.go create mode 100644 google/resource_certificate_manager_dns_authorization_sweeper_test.go create mode 100644 website/docs/r/certificate_manager_certificate.html.markdown create mode 100644 website/docs/r/certificate_manager_dns_authorization.html.markdown diff --git a/.changelog/6004.txt b/.changelog/6004.txt new file mode 100644 index 00000000000..28b403dde92 --- /dev/null +++ b/.changelog/6004.txt @@ -0,0 +1,6 @@ +```release-note:new-resource +`google_certificate_manager_certificate` +``` +```release-note:new-resource +`google_certificate_manager_dns_authorization` +``` diff --git a/google/certificate_manager_operation.go b/google/certificate_manager_operation.go new file mode 100644 index 00000000000..8e71c2cc07d --- /dev/null +++ b/google/certificate_manager_operation.go @@ -0,0 +1,61 @@ +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** Type: MMv1 *** +// +// ---------------------------------------------------------------------------- +// +// 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" + "time" +) + +type CertificateManagerOperationWaiter struct { + Config *Config + UserAgent string + Project string + CommonOperationWaiter +} + +func (w *CertificateManagerOperationWaiter) QueryOp() (interface{}, error) { + if w == nil { + return nil, fmt.Errorf("Cannot query operation, it's unset or nil.") + } + // Returns the proper get. + url := fmt.Sprintf("%s%s", w.Config.CertificateManagerBasePath, w.CommonOperationWaiter.Op.Name) + + return sendRequest(w.Config, "GET", w.Project, url, w.UserAgent, nil) +} + +func createCertificateManagerWaiter(config *Config, op map[string]interface{}, project, activity, userAgent string) (*CertificateManagerOperationWaiter, error) { + w := &CertificateManagerOperationWaiter{ + Config: config, + UserAgent: userAgent, + Project: project, + } + if err := w.CommonOperationWaiter.SetOp(op); err != nil { + return nil, err + } + return w, nil +} + +func certificateManagerOperationWaitTime(config *Config, op map[string]interface{}, project, activity, userAgent string, timeout time.Duration) error { + if val, ok := op["name"]; !ok || val == "" { + // This was a synchronous call - there is no operation to wait for. + return nil + } + w, err := createCertificateManagerWaiter(config, op, project, activity, userAgent) + if err != nil { + // If w is nil, the op was synchronous. + return err + } + return OperationWait(w, activity, timeout, config.PollInterval) +} diff --git a/google/config.go b/google/config.go index 2526c3485f7..18d09d9aa17 100644 --- a/google/config.go +++ b/google/config.go @@ -171,6 +171,7 @@ type Config struct { BigtableBasePath string BillingBasePath string BinaryAuthorizationBasePath string + CertificateManagerBasePath string CloudAssetBasePath string CloudBuildBasePath string CloudFunctionsBasePath string @@ -271,6 +272,7 @@ const BigqueryReservationBasePathKey = "BigqueryReservation" const BigtableBasePathKey = "Bigtable" const BillingBasePathKey = "Billing" const BinaryAuthorizationBasePathKey = "BinaryAuthorization" +const CertificateManagerBasePathKey = "CertificateManager" const CloudAssetBasePathKey = "CloudAsset" const CloudBuildBasePathKey = "CloudBuild" const CloudFunctionsBasePathKey = "CloudFunctions" @@ -353,6 +355,7 @@ var DefaultBasePaths = map[string]string{ BigtableBasePathKey: "https://bigtableadmin.googleapis.com/v2/", BillingBasePathKey: "https://billingbudgets.googleapis.com/v1/", BinaryAuthorizationBasePathKey: "https://binaryauthorization.googleapis.com/v1/", + CertificateManagerBasePathKey: "https://certificatemanager.googleapis.com/v1/", CloudAssetBasePathKey: "https://cloudasset.googleapis.com/v1/", CloudBuildBasePathKey: "https://cloudbuild.googleapis.com/v1/", CloudFunctionsBasePathKey: "https://cloudfunctions.googleapis.com/v1/", @@ -1197,6 +1200,7 @@ func ConfigureBasePaths(c *Config) { c.BigtableBasePath = DefaultBasePaths[BigtableBasePathKey] c.BillingBasePath = DefaultBasePaths[BillingBasePathKey] c.BinaryAuthorizationBasePath = DefaultBasePaths[BinaryAuthorizationBasePathKey] + c.CertificateManagerBasePath = DefaultBasePaths[CertificateManagerBasePathKey] c.CloudAssetBasePath = DefaultBasePaths[CloudAssetBasePathKey] c.CloudBuildBasePath = DefaultBasePaths[CloudBuildBasePathKey] c.CloudFunctionsBasePath = DefaultBasePaths[CloudFunctionsBasePathKey] diff --git a/google/provider.go b/google/provider.go index 98cd0370294..b918a73bf3d 100644 --- a/google/provider.go +++ b/google/provider.go @@ -237,6 +237,14 @@ func Provider() *schema.Provider { "GOOGLE_BINARY_AUTHORIZATION_CUSTOM_ENDPOINT", }, DefaultBasePaths[BinaryAuthorizationBasePathKey]), }, + "certificate_manager_custom_endpoint": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validateCustomEndpoint, + DefaultFunc: schema.MultiEnvDefaultFunc([]string{ + "GOOGLE_CERTIFICATE_MANAGER_CUSTOM_ENDPOINT", + }, DefaultBasePaths[CertificateManagerBasePathKey]), + }, "cloud_asset_custom_endpoint": { Type: schema.TypeString, Optional: true, @@ -831,9 +839,9 @@ func Provider() *schema.Provider { return provider } -// Generated resources: 217 +// Generated resources: 219 // Generated IAM resources: 108 -// Total generated resources: 325 +// Total generated resources: 327 func ResourceMap() map[string]*schema.Resource { resourceMap, _ := ResourceMapWithErrors() return resourceMap @@ -891,6 +899,8 @@ func ResourceMapWithErrors() (map[string]*schema.Resource, error) { "google_binary_authorization_attestor_iam_member": ResourceIamMember(BinaryAuthorizationAttestorIamSchema, BinaryAuthorizationAttestorIamUpdaterProducer, BinaryAuthorizationAttestorIdParseFunc), "google_binary_authorization_attestor_iam_policy": ResourceIamPolicy(BinaryAuthorizationAttestorIamSchema, BinaryAuthorizationAttestorIamUpdaterProducer, BinaryAuthorizationAttestorIdParseFunc), "google_binary_authorization_policy": resourceBinaryAuthorizationPolicy(), + "google_certificate_manager_dns_authorization": resourceCertificateManagerDnsAuthorization(), + "google_certificate_manager_certificate": resourceCertificateManagerCertificate(), "google_cloud_asset_project_feed": resourceCloudAssetProjectFeed(), "google_cloud_asset_folder_feed": resourceCloudAssetFolderFeed(), "google_cloud_asset_organization_feed": resourceCloudAssetOrganizationFeed(), @@ -1423,6 +1433,7 @@ func providerConfigure(ctx context.Context, d *schema.ResourceData, p *schema.Pr config.BigtableBasePath = d.Get("bigtable_custom_endpoint").(string) config.BillingBasePath = d.Get("billing_custom_endpoint").(string) config.BinaryAuthorizationBasePath = d.Get("binary_authorization_custom_endpoint").(string) + config.CertificateManagerBasePath = d.Get("certificate_manager_custom_endpoint").(string) config.CloudAssetBasePath = d.Get("cloud_asset_custom_endpoint").(string) config.CloudBuildBasePath = d.Get("cloud_build_custom_endpoint").(string) config.CloudFunctionsBasePath = d.Get("cloud_functions_custom_endpoint").(string) diff --git a/google/resource_certificate_manager_certificate.go b/google/resource_certificate_manager_certificate.go new file mode 100644 index 00000000000..535f2605375 --- /dev/null +++ b/google/resource_certificate_manager_certificate.go @@ -0,0 +1,594 @@ +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** Type: MMv1 *** +// +// ---------------------------------------------------------------------------- +// +// 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" + "strings" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func resourceCertificateManagerCertificate() *schema.Resource { + return &schema.Resource{ + Create: resourceCertificateManagerCertificateCreate, + Read: resourceCertificateManagerCertificateRead, + Update: resourceCertificateManagerCertificateUpdate, + Delete: resourceCertificateManagerCertificateDelete, + + Importer: &schema.ResourceImporter{ + State: resourceCertificateManagerCertificateImport, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(20 * time.Minute), + Update: schema.DefaultTimeout(20 * time.Minute), + Delete: schema.DefaultTimeout(20 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `A user-defined name of the certificate. Certificate names must be unique +The name must be 1-64 characters long, and match the regular expression [a-zA-Z][a-zA-Z0-9_-]* which means the first character must be a letter, +and all following characters must be a dash, underscore, letter or digit.`, + }, + "description": { + Type: schema.TypeString, + Optional: true, + Description: `A human-readable description of the resource.`, + }, + "labels": { + Type: schema.TypeMap, + Optional: true, + Description: `Set of label tags associated with the EdgeCache resource.`, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "managed": { + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Description: `Configuration and state of a Managed Certificate. +Certificate Manager provisions and renews Managed Certificates +automatically, for as long as it's authorized to do so.`, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "dns_authorizations": { + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Description: `Authorizations that will be used for performing domain authorization`, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "domains": { + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Description: `The domains for which a managed SSL certificate will be generated. +Wildcard domains are only supported with DNS challenge resolution`, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "state": { + Type: schema.TypeString, + Computed: true, + Description: `State of the managed certificate resource.`, + }, + }, + }, + ExactlyOneOf: []string{"self_managed", "managed"}, + }, + "scope": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: validateEnum([]string{"DEFAULT", "EDGE_CACHE", ""}), + Description: `The scope of the certificate. + +Certificates with default scope are served from core Google data centers. +If unsure, choose this option. + +Certificates with scope EDGE_CACHE are special-purposed certificates, +served from non-core Google data centers. +Currently allowed only for managed certificates. Default value: "DEFAULT" Possible values: ["DEFAULT", "EDGE_CACHE"]`, + Default: "DEFAULT", + }, + "self_managed": { + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Description: `Certificate data for a SelfManaged Certificate. +SelfManaged Certificates are uploaded by the user. Updating such +certificates before they expire remains the user's responsibility.`, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "certificate_pem": { + Type: schema.TypeString, + Required: true, + Description: `The certificate chain in PEM-encoded form. + +Leaf certificate comes first, followed by intermediate ones if any.`, + Sensitive: true, + }, + "private_key_pem": { + Type: schema.TypeString, + Required: true, + Description: `The private key of the leaf certificate in PEM-encoded form.`, + Sensitive: true, + }, + }, + }, + ExactlyOneOf: []string{"self_managed", "managed"}, + }, + "project": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, + }, + UseJSONNumber: true, + } +} + +func resourceCertificateManagerCertificateCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + userAgent, err := generateUserAgentString(d, config.userAgent) + if err != nil { + return err + } + + obj := make(map[string]interface{}) + descriptionProp, err := expandCertificateManagerCertificateDescription(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 + } + labelsProp, err := expandCertificateManagerCertificateLabels(d.Get("labels"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("labels"); !isEmptyValue(reflect.ValueOf(labelsProp)) && (ok || !reflect.DeepEqual(v, labelsProp)) { + obj["labels"] = labelsProp + } + scopeProp, err := expandCertificateManagerCertificateScope(d.Get("scope"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("scope"); !isEmptyValue(reflect.ValueOf(scopeProp)) && (ok || !reflect.DeepEqual(v, scopeProp)) { + obj["scope"] = scopeProp + } + selfManagedProp, err := expandCertificateManagerCertificateSelfManaged(d.Get("self_managed"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("self_managed"); !isEmptyValue(reflect.ValueOf(selfManagedProp)) && (ok || !reflect.DeepEqual(v, selfManagedProp)) { + obj["selfManaged"] = selfManagedProp + } + managedProp, err := expandCertificateManagerCertificateManaged(d.Get("managed"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("managed"); !isEmptyValue(reflect.ValueOf(managedProp)) && (ok || !reflect.DeepEqual(v, managedProp)) { + obj["managed"] = managedProp + } + + url, err := replaceVars(d, config, "{{CertificateManagerBasePath}}projects/{{project}}/locations/global/certificates?certificateId={{name}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Creating new Certificate: %#v", obj) + billingProject := "" + + project, err := getProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for Certificate: %s", err) + } + billingProject = project + + // err == nil indicates that the billing_project value was found + if bp, err := getBillingProject(d, config); err == nil { + billingProject = bp + } + + res, err := sendRequestWithTimeout(config, "POST", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutCreate)) + if err != nil { + return fmt.Errorf("Error creating Certificate: %s", err) + } + + // Store the ID now + id, err := replaceVars(d, config, "projects/{{project}}/locations/global/certificates/{{name}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + err = certificateManagerOperationWaitTime( + config, res, project, "Creating Certificate", userAgent, + d.Timeout(schema.TimeoutCreate)) + + if err != nil { + // The resource didn't actually create + d.SetId("") + return fmt.Errorf("Error waiting to create Certificate: %s", err) + } + + log.Printf("[DEBUG] Finished creating Certificate %q: %#v", d.Id(), res) + + return resourceCertificateManagerCertificateRead(d, meta) +} + +func resourceCertificateManagerCertificateRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + userAgent, err := generateUserAgentString(d, config.userAgent) + if err != nil { + return err + } + + url, err := replaceVars(d, config, "{{CertificateManagerBasePath}}projects/{{project}}/locations/global/certificates/{{name}}") + if err != nil { + return err + } + + billingProject := "" + + project, err := getProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for Certificate: %s", err) + } + billingProject = project + + // err == nil indicates that the billing_project value was found + if bp, err := getBillingProject(d, config); err == nil { + billingProject = bp + } + + res, err := sendRequest(config, "GET", billingProject, url, userAgent, nil) + if err != nil { + return handleNotFoundError(err, d, fmt.Sprintf("CertificateManagerCertificate %q", d.Id())) + } + + if err := d.Set("project", project); err != nil { + return fmt.Errorf("Error reading Certificate: %s", err) + } + + if err := d.Set("description", flattenCertificateManagerCertificateDescription(res["description"], d, config)); err != nil { + return fmt.Errorf("Error reading Certificate: %s", err) + } + if err := d.Set("labels", flattenCertificateManagerCertificateLabels(res["labels"], d, config)); err != nil { + return fmt.Errorf("Error reading Certificate: %s", err) + } + if err := d.Set("scope", flattenCertificateManagerCertificateScope(res["scope"], d, config)); err != nil { + return fmt.Errorf("Error reading Certificate: %s", err) + } + if err := d.Set("self_managed", flattenCertificateManagerCertificateSelfManaged(res["selfManaged"], d, config)); err != nil { + return fmt.Errorf("Error reading Certificate: %s", err) + } + if err := d.Set("managed", flattenCertificateManagerCertificateManaged(res["managed"], d, config)); err != nil { + return fmt.Errorf("Error reading Certificate: %s", err) + } + + return nil +} + +func resourceCertificateManagerCertificateUpdate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + userAgent, err := generateUserAgentString(d, config.userAgent) + if err != nil { + return err + } + + billingProject := "" + + project, err := getProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for Certificate: %s", err) + } + billingProject = project + + obj := make(map[string]interface{}) + descriptionProp, err := expandCertificateManagerCertificateDescription(d.Get("description"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("description"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, descriptionProp)) { + obj["description"] = descriptionProp + } + labelsProp, err := expandCertificateManagerCertificateLabels(d.Get("labels"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("labels"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, labelsProp)) { + obj["labels"] = labelsProp + } + + url, err := replaceVars(d, config, "{{CertificateManagerBasePath}}projects/{{project}}/locations/global/certificates/{{name}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Updating Certificate %q: %#v", d.Id(), obj) + updateMask := []string{} + + if d.HasChange("description") { + updateMask = append(updateMask, "description") + } + + if d.HasChange("labels") { + updateMask = append(updateMask, "labels") + } + // updateMask is a URL parameter but not present in the schema, so replaceVars + // won't set it + url, err = addQueryParams(url, map[string]string{"updateMask": strings.Join(updateMask, ",")}) + if err != nil { + return err + } + + // err == nil indicates that the billing_project value was found + if bp, err := getBillingProject(d, config); err == nil { + billingProject = bp + } + + res, err := sendRequestWithTimeout(config, "PATCH", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutUpdate)) + + if err != nil { + return fmt.Errorf("Error updating Certificate %q: %s", d.Id(), err) + } else { + log.Printf("[DEBUG] Finished updating Certificate %q: %#v", d.Id(), res) + } + + err = certificateManagerOperationWaitTime( + config, res, project, "Updating Certificate", userAgent, + d.Timeout(schema.TimeoutUpdate)) + + if err != nil { + return err + } + + return resourceCertificateManagerCertificateRead(d, meta) +} + +func resourceCertificateManagerCertificateDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + userAgent, err := generateUserAgentString(d, config.userAgent) + if err != nil { + return err + } + + billingProject := "" + + project, err := getProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for Certificate: %s", err) + } + billingProject = project + + url, err := replaceVars(d, config, "{{CertificateManagerBasePath}}projects/{{project}}/locations/global/certificates/{{name}}") + if err != nil { + return err + } + + var obj map[string]interface{} + log.Printf("[DEBUG] Deleting Certificate %q", d.Id()) + + // err == nil indicates that the billing_project value was found + if bp, err := getBillingProject(d, config); err == nil { + billingProject = bp + } + + res, err := sendRequestWithTimeout(config, "DELETE", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutDelete)) + if err != nil { + return handleNotFoundError(err, d, "Certificate") + } + + err = certificateManagerOperationWaitTime( + config, res, project, "Deleting Certificate", userAgent, + d.Timeout(schema.TimeoutDelete)) + + if err != nil { + return err + } + + log.Printf("[DEBUG] Finished deleting Certificate %q: %#v", d.Id(), res) + return nil +} + +func resourceCertificateManagerCertificateImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + config := meta.(*Config) + if err := parseImportId([]string{ + "projects/(?P[^/]+)/locations/global/certificates/(?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}}/locations/global/certificates/{{name}}") + if err != nil { + return nil, fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + return []*schema.ResourceData{d}, nil +} + +func flattenCertificateManagerCertificateDescription(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenCertificateManagerCertificateLabels(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenCertificateManagerCertificateScope(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenCertificateManagerCertificateSelfManaged(v interface{}, d *schema.ResourceData, config *Config) interface{} { + if v == nil { + return nil + } + original := v.(map[string]interface{}) + if len(original) == 0 { + return nil + } + transformed := make(map[string]interface{}) + transformed["certificate_pem"] = + flattenCertificateManagerCertificateSelfManagedCertificatePem(original["certificatePem"], d, config) + transformed["private_key_pem"] = + flattenCertificateManagerCertificateSelfManagedPrivateKeyPem(original["privateKeyPem"], d, config) + return []interface{}{transformed} +} +func flattenCertificateManagerCertificateSelfManagedCertificatePem(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenCertificateManagerCertificateSelfManagedPrivateKeyPem(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenCertificateManagerCertificateManaged(v interface{}, d *schema.ResourceData, config *Config) interface{} { + if v == nil { + return nil + } + original := v.(map[string]interface{}) + if len(original) == 0 { + return nil + } + transformed := make(map[string]interface{}) + transformed["state"] = + flattenCertificateManagerCertificateManagedState(original["state"], d, config) + transformed["domains"] = + flattenCertificateManagerCertificateManagedDomains(original["domains"], d, config) + transformed["dns_authorizations"] = + flattenCertificateManagerCertificateManagedDnsAuthorizations(original["dnsAuthorizations"], d, config) + return []interface{}{transformed} +} +func flattenCertificateManagerCertificateManagedState(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenCertificateManagerCertificateManagedDomains(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenCertificateManagerCertificateManagedDnsAuthorizations(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return d.Get("managed.0.dns_authorizations") +} + +func expandCertificateManagerCertificateDescription(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func expandCertificateManagerCertificateLabels(v interface{}, d TerraformResourceData, config *Config) (map[string]string, error) { + if v == nil { + return map[string]string{}, nil + } + m := make(map[string]string) + for k, val := range v.(map[string]interface{}) { + m[k] = val.(string) + } + return m, nil +} + +func expandCertificateManagerCertificateScope(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func expandCertificateManagerCertificateSelfManaged(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + l := v.([]interface{}) + if len(l) == 0 || l[0] == nil { + return nil, nil + } + raw := l[0] + original := raw.(map[string]interface{}) + transformed := make(map[string]interface{}) + + transformedCertificatePem, err := expandCertificateManagerCertificateSelfManagedCertificatePem(original["certificate_pem"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedCertificatePem); val.IsValid() && !isEmptyValue(val) { + transformed["certificatePem"] = transformedCertificatePem + } + + transformedPrivateKeyPem, err := expandCertificateManagerCertificateSelfManagedPrivateKeyPem(original["private_key_pem"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedPrivateKeyPem); val.IsValid() && !isEmptyValue(val) { + transformed["privateKeyPem"] = transformedPrivateKeyPem + } + + return transformed, nil +} + +func expandCertificateManagerCertificateSelfManagedCertificatePem(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func expandCertificateManagerCertificateSelfManagedPrivateKeyPem(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func expandCertificateManagerCertificateManaged(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + l := v.([]interface{}) + if len(l) == 0 || l[0] == nil { + return nil, nil + } + raw := l[0] + original := raw.(map[string]interface{}) + transformed := make(map[string]interface{}) + + transformedState, err := expandCertificateManagerCertificateManagedState(original["state"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedState); val.IsValid() && !isEmptyValue(val) { + transformed["state"] = transformedState + } + + transformedDomains, err := expandCertificateManagerCertificateManagedDomains(original["domains"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedDomains); val.IsValid() && !isEmptyValue(val) { + transformed["domains"] = transformedDomains + } + + transformedDnsAuthorizations, err := expandCertificateManagerCertificateManagedDnsAuthorizations(original["dns_authorizations"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedDnsAuthorizations); val.IsValid() && !isEmptyValue(val) { + transformed["dnsAuthorizations"] = transformedDnsAuthorizations + } + + return transformed, nil +} + +func expandCertificateManagerCertificateManagedState(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func expandCertificateManagerCertificateManagedDomains(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func expandCertificateManagerCertificateManagedDnsAuthorizations(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} diff --git a/google/resource_certificate_manager_certificate_generated_test.go b/google/resource_certificate_manager_certificate_generated_test.go new file mode 100644 index 00000000000..a52e0f40e81 --- /dev/null +++ b/google/resource_certificate_manager_certificate_generated_test.go @@ -0,0 +1,115 @@ +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** Type: MMv1 *** +// +// ---------------------------------------------------------------------------- +// +// 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/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +func TestAccCertificateManagerCertificate_certificateManagerCertificateBasicExample(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": randString(t, 10), + } + + vcrTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckCertificateManagerCertificateDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccCertificateManagerCertificate_certificateManagerCertificateBasicExample(context), + }, + { + ResourceName: "google_certificate_manager_certificate.default", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"name", "managed.0.dns_authorizations"}, + }, + }, + }) +} + +func testAccCertificateManagerCertificate_certificateManagerCertificateBasicExample(context map[string]interface{}) string { + return Nprintf(` +resource "google_certificate_manager_certificate" "default" { + name = "tf-test-dns-cert%{random_suffix}" + description = "The default cert" + scope = "EDGE_CACHE" + managed { + domains = [ + google_certificate_manager_dns_authorization.instance.domain, + google_certificate_manager_dns_authorization.instance2.domain, + ] + dns_authorizations = [ + google_certificate_manager_dns_authorization.instance.id, + google_certificate_manager_dns_authorization.instance2.id, + ] + } +} + + +resource "google_certificate_manager_dns_authorization" "instance" { + name = "tf-test-dns-auth%{random_suffix}" + description = "The default dnss" + domain = "subdomain%{random_suffix}.hashicorptest.com" +} + +resource "google_certificate_manager_dns_authorization" "instance2" { + name = "tf-test-dns-auth2%{random_suffix}" + description = "The default dnss" + domain = "subdomain2%{random_suffix}.hashicorptest.com" +} +`, context) +} + +func testAccCheckCertificateManagerCertificateDestroyProducer(t *testing.T) func(s *terraform.State) error { + return func(s *terraform.State) error { + for name, rs := range s.RootModule().Resources { + if rs.Type != "google_certificate_manager_certificate" { + continue + } + if strings.HasPrefix(name, "data.") { + continue + } + + config := googleProviderConfig(t) + + url, err := replaceVarsForTest(config, rs, "{{CertificateManagerBasePath}}projects/{{project}}/locations/global/certificates/{{name}}") + if err != nil { + return err + } + + billingProject := "" + + if config.BillingProject != "" { + billingProject = config.BillingProject + } + + _, err = sendRequest(config, "GET", billingProject, url, config.userAgent, nil) + if err == nil { + return fmt.Errorf("CertificateManagerCertificate still exists at %s", url) + } + } + + return nil + } +} diff --git a/google/resource_certificate_manager_certificate_sweeper_test.go b/google/resource_certificate_manager_certificate_sweeper_test.go new file mode 100644 index 00000000000..0b25963bb36 --- /dev/null +++ b/google/resource_certificate_manager_certificate_sweeper_test.go @@ -0,0 +1,124 @@ +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** Type: MMv1 *** +// +// ---------------------------------------------------------------------------- +// +// 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" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +func init() { + resource.AddTestSweepers("CertificateManagerCertificate", &resource.Sweeper{ + Name: "CertificateManagerCertificate", + F: testSweepCertificateManagerCertificate, + }) +} + +// At the time of writing, the CI only passes us-central1 as the region +func testSweepCertificateManagerCertificate(region string) error { + resourceName := "CertificateManagerCertificate" + 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 + } + + t := &testing.T{} + billingId := getTestBillingAccountFromEnv(t) + + // Setup variables to replace in list template + d := &ResourceDataMock{ + FieldsInSchema: map[string]interface{}{ + "project": config.Project, + "region": region, + "location": region, + "zone": "-", + "billing_account": billingId, + }, + } + + listTemplate := strings.Split("https://certificatemanager.googleapis.com/v1/projects/{{project}}/locations/global/certificates", "?")[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, config.userAgent, nil) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] Error in response from request %s: %s", listUrl, err) + return nil + } + + resourceList, ok := res["certificates"] + 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) + // Keep count of items that aren't sweepable for logging. + 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)) + // Skip resources that shouldn't be sweeped + if !isSweepableTestResource(name) { + nonPrefixCount++ + continue + } + + deleteTemplate := "https://certificatemanager.googleapis.com/v1/projects/{{project}}/locations/global/certificates/{{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, config.userAgent, 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 were non-sweepable and skipped.", nonPrefixCount) + } + + return nil +} diff --git a/google/resource_certificate_manager_dns_authorization.go b/google/resource_certificate_manager_dns_authorization.go new file mode 100644 index 00000000000..dcfed30c3e7 --- /dev/null +++ b/google/resource_certificate_manager_dns_authorization.go @@ -0,0 +1,430 @@ +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** Type: MMv1 *** +// +// ---------------------------------------------------------------------------- +// +// 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" + "strings" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func resourceCertificateManagerDnsAuthorization() *schema.Resource { + return &schema.Resource{ + Create: resourceCertificateManagerDnsAuthorizationCreate, + Read: resourceCertificateManagerDnsAuthorizationRead, + Update: resourceCertificateManagerDnsAuthorizationUpdate, + Delete: resourceCertificateManagerDnsAuthorizationDelete, + + Importer: &schema.ResourceImporter{ + State: resourceCertificateManagerDnsAuthorizationImport, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(20 * time.Minute), + Update: schema.DefaultTimeout(20 * time.Minute), + Delete: schema.DefaultTimeout(20 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "domain": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `A domain which is being authorized. A DnsAuthorization resource covers a +single domain and its wildcard, e.g. authorization for "example.com" can +be used to issue certificates for "example.com" and "*.example.com".`, + }, + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `Name of the resource; provided by the client when the resource is created. +The name must be 1-64 characters long, and match the regular expression [a-zA-Z][a-zA-Z0-9_-]* which means the first character must be a letter, +and all following characters must be a dash, underscore, letter or digit.`, + }, + "description": { + Type: schema.TypeString, + Optional: true, + Description: `A human-readable description of the resource.`, + }, + "labels": { + Type: schema.TypeMap, + Optional: true, + Description: `Set of label tags associated with the EdgeCache resource.`, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "dns_resource_record": { + Type: schema.TypeList, + Computed: true, + Description: `The structure describing the DNS Resource Record that needs to be added +to DNS configuration for the authorization to be usable by +certificate.`, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "data": { + Type: schema.TypeString, + Computed: true, + Description: `Data of the DNS Resource Record.`, + }, + "name": { + Type: schema.TypeString, + Computed: true, + Description: `Fully qualified name of the DNS Resource Record.`, + }, + "type": { + Type: schema.TypeString, + Computed: true, + Description: `Type of the DNS Resource Record.`, + }, + }, + }, + }, + "project": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, + }, + UseJSONNumber: true, + } +} + +func resourceCertificateManagerDnsAuthorizationCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + userAgent, err := generateUserAgentString(d, config.userAgent) + if err != nil { + return err + } + + obj := make(map[string]interface{}) + descriptionProp, err := expandCertificateManagerDnsAuthorizationDescription(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 + } + labelsProp, err := expandCertificateManagerDnsAuthorizationLabels(d.Get("labels"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("labels"); !isEmptyValue(reflect.ValueOf(labelsProp)) && (ok || !reflect.DeepEqual(v, labelsProp)) { + obj["labels"] = labelsProp + } + domainProp, err := expandCertificateManagerDnsAuthorizationDomain(d.Get("domain"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("domain"); !isEmptyValue(reflect.ValueOf(domainProp)) && (ok || !reflect.DeepEqual(v, domainProp)) { + obj["domain"] = domainProp + } + + url, err := replaceVars(d, config, "{{CertificateManagerBasePath}}projects/{{project}}/locations/global/dnsAuthorizations?dnsAuthorizationId={{name}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Creating new DnsAuthorization: %#v", obj) + billingProject := "" + + project, err := getProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for DnsAuthorization: %s", err) + } + billingProject = project + + // err == nil indicates that the billing_project value was found + if bp, err := getBillingProject(d, config); err == nil { + billingProject = bp + } + + res, err := sendRequestWithTimeout(config, "POST", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutCreate)) + if err != nil { + return fmt.Errorf("Error creating DnsAuthorization: %s", err) + } + + // Store the ID now + id, err := replaceVars(d, config, "projects/{{project}}/locations/global/dnsAuthorizations/{{name}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + err = certificateManagerOperationWaitTime( + config, res, project, "Creating DnsAuthorization", userAgent, + d.Timeout(schema.TimeoutCreate)) + + if err != nil { + // The resource didn't actually create + d.SetId("") + return fmt.Errorf("Error waiting to create DnsAuthorization: %s", err) + } + + log.Printf("[DEBUG] Finished creating DnsAuthorization %q: %#v", d.Id(), res) + + return resourceCertificateManagerDnsAuthorizationRead(d, meta) +} + +func resourceCertificateManagerDnsAuthorizationRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + userAgent, err := generateUserAgentString(d, config.userAgent) + if err != nil { + return err + } + + url, err := replaceVars(d, config, "{{CertificateManagerBasePath}}projects/{{project}}/locations/global/dnsAuthorizations/{{name}}") + if err != nil { + return err + } + + billingProject := "" + + project, err := getProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for DnsAuthorization: %s", err) + } + billingProject = project + + // err == nil indicates that the billing_project value was found + if bp, err := getBillingProject(d, config); err == nil { + billingProject = bp + } + + res, err := sendRequest(config, "GET", billingProject, url, userAgent, nil) + if err != nil { + return handleNotFoundError(err, d, fmt.Sprintf("CertificateManagerDnsAuthorization %q", d.Id())) + } + + if err := d.Set("project", project); err != nil { + return fmt.Errorf("Error reading DnsAuthorization: %s", err) + } + + if err := d.Set("description", flattenCertificateManagerDnsAuthorizationDescription(res["description"], d, config)); err != nil { + return fmt.Errorf("Error reading DnsAuthorization: %s", err) + } + if err := d.Set("labels", flattenCertificateManagerDnsAuthorizationLabels(res["labels"], d, config)); err != nil { + return fmt.Errorf("Error reading DnsAuthorization: %s", err) + } + if err := d.Set("domain", flattenCertificateManagerDnsAuthorizationDomain(res["domain"], d, config)); err != nil { + return fmt.Errorf("Error reading DnsAuthorization: %s", err) + } + if err := d.Set("dns_resource_record", flattenCertificateManagerDnsAuthorizationDnsResourceRecord(res["dnsResourceRecord"], d, config)); err != nil { + return fmt.Errorf("Error reading DnsAuthorization: %s", err) + } + + return nil +} + +func resourceCertificateManagerDnsAuthorizationUpdate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + userAgent, err := generateUserAgentString(d, config.userAgent) + if err != nil { + return err + } + + billingProject := "" + + project, err := getProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for DnsAuthorization: %s", err) + } + billingProject = project + + obj := make(map[string]interface{}) + descriptionProp, err := expandCertificateManagerDnsAuthorizationDescription(d.Get("description"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("description"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, descriptionProp)) { + obj["description"] = descriptionProp + } + labelsProp, err := expandCertificateManagerDnsAuthorizationLabels(d.Get("labels"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("labels"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, labelsProp)) { + obj["labels"] = labelsProp + } + + url, err := replaceVars(d, config, "{{CertificateManagerBasePath}}projects/{{project}}/locations/global/dnsAuthorizations/{{name}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Updating DnsAuthorization %q: %#v", d.Id(), obj) + updateMask := []string{} + + if d.HasChange("description") { + updateMask = append(updateMask, "description") + } + + if d.HasChange("labels") { + updateMask = append(updateMask, "labels") + } + // updateMask is a URL parameter but not present in the schema, so replaceVars + // won't set it + url, err = addQueryParams(url, map[string]string{"updateMask": strings.Join(updateMask, ",")}) + if err != nil { + return err + } + + // err == nil indicates that the billing_project value was found + if bp, err := getBillingProject(d, config); err == nil { + billingProject = bp + } + + res, err := sendRequestWithTimeout(config, "PATCH", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutUpdate)) + + if err != nil { + return fmt.Errorf("Error updating DnsAuthorization %q: %s", d.Id(), err) + } else { + log.Printf("[DEBUG] Finished updating DnsAuthorization %q: %#v", d.Id(), res) + } + + err = certificateManagerOperationWaitTime( + config, res, project, "Updating DnsAuthorization", userAgent, + d.Timeout(schema.TimeoutUpdate)) + + if err != nil { + return err + } + + return resourceCertificateManagerDnsAuthorizationRead(d, meta) +} + +func resourceCertificateManagerDnsAuthorizationDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + userAgent, err := generateUserAgentString(d, config.userAgent) + if err != nil { + return err + } + + billingProject := "" + + project, err := getProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for DnsAuthorization: %s", err) + } + billingProject = project + + url, err := replaceVars(d, config, "{{CertificateManagerBasePath}}projects/{{project}}/locations/global/dnsAuthorizations/{{name}}") + if err != nil { + return err + } + + var obj map[string]interface{} + log.Printf("[DEBUG] Deleting DnsAuthorization %q", d.Id()) + + // err == nil indicates that the billing_project value was found + if bp, err := getBillingProject(d, config); err == nil { + billingProject = bp + } + + res, err := sendRequestWithTimeout(config, "DELETE", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutDelete)) + if err != nil { + return handleNotFoundError(err, d, "DnsAuthorization") + } + + err = certificateManagerOperationWaitTime( + config, res, project, "Deleting DnsAuthorization", userAgent, + d.Timeout(schema.TimeoutDelete)) + + if err != nil { + return err + } + + log.Printf("[DEBUG] Finished deleting DnsAuthorization %q: %#v", d.Id(), res) + return nil +} + +func resourceCertificateManagerDnsAuthorizationImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + config := meta.(*Config) + if err := parseImportId([]string{ + "projects/(?P[^/]+)/locations/global/dnsAuthorizations/(?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}}/locations/global/dnsAuthorizations/{{name}}") + if err != nil { + return nil, fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + return []*schema.ResourceData{d}, nil +} + +func flattenCertificateManagerDnsAuthorizationDescription(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenCertificateManagerDnsAuthorizationLabels(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenCertificateManagerDnsAuthorizationDomain(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenCertificateManagerDnsAuthorizationDnsResourceRecord(v interface{}, d *schema.ResourceData, config *Config) interface{} { + if v == nil { + return nil + } + original := v.(map[string]interface{}) + if len(original) == 0 { + return nil + } + transformed := make(map[string]interface{}) + transformed["name"] = + flattenCertificateManagerDnsAuthorizationDnsResourceRecordName(original["name"], d, config) + transformed["type"] = + flattenCertificateManagerDnsAuthorizationDnsResourceRecordType(original["type"], d, config) + transformed["data"] = + flattenCertificateManagerDnsAuthorizationDnsResourceRecordData(original["data"], d, config) + return []interface{}{transformed} +} +func flattenCertificateManagerDnsAuthorizationDnsResourceRecordName(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenCertificateManagerDnsAuthorizationDnsResourceRecordType(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenCertificateManagerDnsAuthorizationDnsResourceRecordData(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func expandCertificateManagerDnsAuthorizationDescription(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func expandCertificateManagerDnsAuthorizationLabels(v interface{}, d TerraformResourceData, config *Config) (map[string]string, error) { + if v == nil { + return map[string]string{}, nil + } + m := make(map[string]string) + for k, val := range v.(map[string]interface{}) { + m[k] = val.(string) + } + return m, nil +} + +func expandCertificateManagerDnsAuthorizationDomain(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} diff --git a/google/resource_certificate_manager_dns_authorization_generated_test.go b/google/resource_certificate_manager_dns_authorization_generated_test.go new file mode 100644 index 00000000000..0983ef702c3 --- /dev/null +++ b/google/resource_certificate_manager_dns_authorization_generated_test.go @@ -0,0 +1,104 @@ +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** Type: MMv1 *** +// +// ---------------------------------------------------------------------------- +// +// 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/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +func TestAccCertificateManagerDnsAuthorization_certificateManagerDnsAuthorizationBasicExample(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": randString(t, 10), + } + + vcrTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckCertificateManagerDnsAuthorizationDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccCertificateManagerDnsAuthorization_certificateManagerDnsAuthorizationBasicExample(context), + }, + { + ResourceName: "google_certificate_manager_dns_authorization.default", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"name"}, + }, + }, + }) +} + +func testAccCertificateManagerDnsAuthorization_certificateManagerDnsAuthorizationBasicExample(context map[string]interface{}) string { + return Nprintf(` +resource "google_certificate_manager_dns_authorization" "default" { + name = "tf-test-dns-auth%{random_suffix}" + description = "The default dnss" + domain = "%{random_suffix}.hashicorptest.com" +} + +output "record_name_to_insert" { + value = google_certificate_manager_dns_authorization.default.dns_resource_record.0.name +} + +output "record_type_to_insert" { + value = google_certificate_manager_dns_authorization.default.dns_resource_record.0.type +} + +output "record_data_to_insert" { + value = google_certificate_manager_dns_authorization.default.dns_resource_record.0.data +} +`, context) +} + +func testAccCheckCertificateManagerDnsAuthorizationDestroyProducer(t *testing.T) func(s *terraform.State) error { + return func(s *terraform.State) error { + for name, rs := range s.RootModule().Resources { + if rs.Type != "google_certificate_manager_dns_authorization" { + continue + } + if strings.HasPrefix(name, "data.") { + continue + } + + config := googleProviderConfig(t) + + url, err := replaceVarsForTest(config, rs, "{{CertificateManagerBasePath}}projects/{{project}}/locations/global/dnsAuthorizations/{{name}}") + if err != nil { + return err + } + + billingProject := "" + + if config.BillingProject != "" { + billingProject = config.BillingProject + } + + _, err = sendRequest(config, "GET", billingProject, url, config.userAgent, nil) + if err == nil { + return fmt.Errorf("CertificateManagerDnsAuthorization still exists at %s", url) + } + } + + return nil + } +} diff --git a/google/resource_certificate_manager_dns_authorization_sweeper_test.go b/google/resource_certificate_manager_dns_authorization_sweeper_test.go new file mode 100644 index 00000000000..ae2bdbf9c6a --- /dev/null +++ b/google/resource_certificate_manager_dns_authorization_sweeper_test.go @@ -0,0 +1,124 @@ +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** Type: MMv1 *** +// +// ---------------------------------------------------------------------------- +// +// 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" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +func init() { + resource.AddTestSweepers("CertificateManagerDnsAuthorization", &resource.Sweeper{ + Name: "CertificateManagerDnsAuthorization", + F: testSweepCertificateManagerDnsAuthorization, + }) +} + +// At the time of writing, the CI only passes us-central1 as the region +func testSweepCertificateManagerDnsAuthorization(region string) error { + resourceName := "CertificateManagerDnsAuthorization" + 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 + } + + t := &testing.T{} + billingId := getTestBillingAccountFromEnv(t) + + // Setup variables to replace in list template + d := &ResourceDataMock{ + FieldsInSchema: map[string]interface{}{ + "project": config.Project, + "region": region, + "location": region, + "zone": "-", + "billing_account": billingId, + }, + } + + listTemplate := strings.Split("https://certificatemanager.googleapis.com/v1/projects/{{project}}/locations/global/dnsAuthorizations", "?")[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, config.userAgent, nil) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] Error in response from request %s: %s", listUrl, err) + return nil + } + + resourceList, ok := res["dnsAuthorizations"] + 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) + // Keep count of items that aren't sweepable for logging. + 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)) + // Skip resources that shouldn't be sweeped + if !isSweepableTestResource(name) { + nonPrefixCount++ + continue + } + + deleteTemplate := "https://certificatemanager.googleapis.com/v1/projects/{{project}}/locations/global/dnsAuthorizations/{{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, config.userAgent, 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 were non-sweepable and skipped.", nonPrefixCount) + } + + return nil +} diff --git a/google/resource_clouddeploy_delivery_pipeline_generated_test.go b/google/resource_clouddeploy_delivery_pipeline_generated_test.go index 2ace6e3b7b6..95b74ca2cfe 100644 --- a/google/resource_clouddeploy_delivery_pipeline_generated_test.go +++ b/google/resource_clouddeploy_delivery_pipeline_generated_test.go @@ -106,17 +106,17 @@ resource "google_clouddeploy_delivery_pipeline" "primary" { name = "tf-test-pipeline%{random_suffix}" annotations = { - my_third_annotation = "example-annotation-3" - my_second_annotation = "updated-example-annotation-2" + + my_third_annotation = "example-annotation-3" } description = "updated description" labels = { - my_second_label = "updated-example-label-2" - my_third_label = "example-label-3" + + my_second_label = "updated-example-label-2" } project = "%{project_name}" diff --git a/google/resource_clouddeploy_target_generated_test.go b/google/resource_clouddeploy_target_generated_test.go index da4be0b0d46..b1452db3413 100644 --- a/google/resource_clouddeploy_target_generated_test.go +++ b/google/resource_clouddeploy_target_generated_test.go @@ -156,9 +156,9 @@ resource "google_clouddeploy_target" "primary" { name = "tf-test-target%{random_suffix}" annotations = { - my_third_annotation = "example-annotation-3" - my_second_annotation = "updated-example-annotation-2" + + my_third_annotation = "example-annotation-3" } description = "updated description" @@ -175,9 +175,9 @@ resource "google_clouddeploy_target" "primary" { } labels = { - my_second_label = "updated-example-label-2" - my_third_label = "example-label-3" + + my_second_label = "updated-example-label-2" } project = "%{project_name}" diff --git a/website/docs/r/certificate_manager_certificate.html.markdown b/website/docs/r/certificate_manager_certificate.html.markdown new file mode 100644 index 00000000000..d7b6e916749 --- /dev/null +++ b/website/docs/r/certificate_manager_certificate.html.markdown @@ -0,0 +1,181 @@ +--- +# ---------------------------------------------------------------------------- +# +# *** AUTO GENERATED CODE *** Type: MMv1 *** +# +# ---------------------------------------------------------------------------- +# +# 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: "Certificate manager" +layout: "google" +page_title: "Google: google_certificate_manager_certificate" +sidebar_current: "docs-google-certificate-manager-certificate" +description: |- + Certificate represents a HTTP-reachable backend for an Certificate. +--- + +# google\_certificate\_manager\_certificate + +Certificate represents a HTTP-reachable backend for an Certificate. + + + +~> **Warning:** These resources require allow-listing to use, and are not openly available to all Cloud customers. Engage with your Cloud account team to discuss how to onboard. + +~> **Warning:** All arguments including `self_managed.certificate_pem` and `self_managed.private_key_pem` will be stored in the raw +state as plain-text. [Read more about sensitive data in state](/language/state/sensitive-data.html). + + +## Example Usage - Certificate Manager Certificate Basic + + +```hcl +resource "google_certificate_manager_certificate" "default" { + name = "dns-cert" + description = "The default cert" + scope = "EDGE_CACHE" + managed { + domains = [ + google_certificate_manager_dns_authorization.instance.domain, + google_certificate_manager_dns_authorization.instance2.domain, + ] + dns_authorizations = [ + google_certificate_manager_dns_authorization.instance.id, + google_certificate_manager_dns_authorization.instance2.id, + ] + } +} + + +resource "google_certificate_manager_dns_authorization" "instance" { + name = "dns-auth" + description = "The default dnss" + domain = "subdomain.hashicorptest.com" +} + +resource "google_certificate_manager_dns_authorization" "instance2" { + name = "dns-auth2" + description = "The default dnss" + domain = "subdomain2.hashicorptest.com" +} +``` + +## Argument Reference + +The following arguments are supported: + + +* `name` - + (Required) + A user-defined name of the certificate. Certificate names must be unique + The name must be 1-64 characters long, and match the regular expression [a-zA-Z][a-zA-Z0-9_-]* which means the first character must be a letter, + and all following characters must be a dash, underscore, letter or digit. + + +- - - + + +* `description` - + (Optional) + A human-readable description of the resource. + +* `labels` - + (Optional) + Set of label tags associated with the EdgeCache resource. + +* `scope` - + (Optional) + The scope of the certificate. + Certificates with default scope are served from core Google data centers. + If unsure, choose this option. + Certificates with scope EDGE_CACHE are special-purposed certificates, + served from non-core Google data centers. + Currently allowed only for managed certificates. + Default value is `DEFAULT`. + Possible values are `DEFAULT` and `EDGE_CACHE`. + +* `self_managed` - + (Optional) + Certificate data for a SelfManaged Certificate. + SelfManaged Certificates are uploaded by the user. Updating such + certificates before they expire remains the user's responsibility. + Structure is [documented below](#nested_self_managed). + +* `managed` - + (Optional) + Configuration and state of a Managed Certificate. + Certificate Manager provisions and renews Managed Certificates + automatically, for as long as it's authorized to do so. + Structure is [documented below](#nested_managed). + +* `project` - (Optional) The ID of the project in which the resource belongs. + If it is not provided, the provider project is used. + + +The `self_managed` block supports: + +* `certificate_pem` - + (Required) + The certificate chain in PEM-encoded form. + Leaf certificate comes first, followed by intermediate ones if any. + **Note**: This property is sensitive and will not be displayed in the plan. + +* `private_key_pem` - + (Required) + The private key of the leaf certificate in PEM-encoded form. + **Note**: This property is sensitive and will not be displayed in the plan. + +The `managed` block supports: + +* `state` - + State of the managed certificate resource. + +* `domains` - + (Optional) + The domains for which a managed SSL certificate will be generated. + Wildcard domains are only supported with DNS challenge resolution + +* `dns_authorizations` - + (Optional) + Authorizations that will be used for performing domain authorization + +## 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}}/locations/global/certificates/{{name}}` + + +## Timeouts + +This resource provides the following +[Timeouts](/docs/configuration/resources.html#timeouts) configuration options: + +- `create` - Default is 20 minutes. +- `update` - Default is 20 minutes. +- `delete` - Default is 20 minutes. + +## Import + + +Certificate can be imported using any of these accepted formats: + +``` +$ terraform import google_certificate_manager_certificate.default projects/{{project}}/locations/global/certificates/{{name}} +$ terraform import google_certificate_manager_certificate.default {{project}}/{{name}} +$ terraform import google_certificate_manager_certificate.default {{name}} +``` + +## User Project Overrides + +This resource supports [User Project Overrides](https://www.terraform.io/docs/providers/google/guides/provider_reference.html#user_project_override). diff --git a/website/docs/r/certificate_manager_dns_authorization.html.markdown b/website/docs/r/certificate_manager_dns_authorization.html.markdown new file mode 100644 index 00000000000..7b74a982ba6 --- /dev/null +++ b/website/docs/r/certificate_manager_dns_authorization.html.markdown @@ -0,0 +1,138 @@ +--- +# ---------------------------------------------------------------------------- +# +# *** AUTO GENERATED CODE *** Type: MMv1 *** +# +# ---------------------------------------------------------------------------- +# +# 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: "Certificate manager" +layout: "google" +page_title: "Google: google_certificate_manager_dns_authorization" +sidebar_current: "docs-google-certificate-manager-dns-authorization" +description: |- + DnsAuthorization represents a HTTP-reachable backend for an DnsAuthorization. +--- + +# google\_certificate\_manager\_dns\_authorization + +DnsAuthorization represents a HTTP-reachable backend for an DnsAuthorization. + + + +~> **Warning:** These resources require allow-listing to use, and are not openly available to all Cloud customers. Engage with your Cloud account team to discuss how to onboard. + + +## Example Usage - Certificate Manager Dns Authorization Basic + + +```hcl +resource "google_certificate_manager_dns_authorization" "default" { + name = "dns-auth" + description = "The default dnss" + domain = "%{random_suffix}.hashicorptest.com" +} + +output "record_name_to_insert" { + value = google_certificate_manager_dns_authorization.default.dns_resource_record.0.name +} + +output "record_type_to_insert" { + value = google_certificate_manager_dns_authorization.default.dns_resource_record.0.type +} + +output "record_data_to_insert" { + value = google_certificate_manager_dns_authorization.default.dns_resource_record.0.data +} +``` + +## Argument Reference + +The following arguments are supported: + + +* `domain` - + (Required) + A domain which is being authorized. A DnsAuthorization resource covers a + single domain and its wildcard, e.g. authorization for "example.com" can + be used to issue certificates for "example.com" and "*.example.com". + +* `name` - + (Required) + Name of the resource; provided by the client when the resource is created. + The name must be 1-64 characters long, and match the regular expression [a-zA-Z][a-zA-Z0-9_-]* which means the first character must be a letter, + and all following characters must be a dash, underscore, letter or digit. + + +- - - + + +* `description` - + (Optional) + A human-readable description of the resource. + +* `labels` - + (Optional) + Set of label tags associated with the EdgeCache resource. + +* `project` - (Optional) The ID of the project in which the resource belongs. + If it is not provided, the provider project is used. + + +## 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}}/locations/global/dnsAuthorizations/{{name}}` + +* `dns_resource_record` - + The structure describing the DNS Resource Record that needs to be added + to DNS configuration for the authorization to be usable by + certificate. + Structure is [documented below](#nested_dns_resource_record). + + +The `dns_resource_record` block contains: + +* `name` - + Fully qualified name of the DNS Resource Record. + +* `type` - + Type of the DNS Resource Record. + +* `data` - + Data of the DNS Resource Record. + +## Timeouts + +This resource provides the following +[Timeouts](/docs/configuration/resources.html#timeouts) configuration options: + +- `create` - Default is 20 minutes. +- `update` - Default is 20 minutes. +- `delete` - Default is 20 minutes. + +## Import + + +DnsAuthorization can be imported using any of these accepted formats: + +``` +$ terraform import google_certificate_manager_dns_authorization.default projects/{{project}}/locations/global/dnsAuthorizations/{{name}} +$ terraform import google_certificate_manager_dns_authorization.default {{project}}/{{name}} +$ terraform import google_certificate_manager_dns_authorization.default {{name}} +``` + +## User Project Overrides + +This resource supports [User Project Overrides](https://www.terraform.io/docs/providers/google/guides/provider_reference.html#user_project_override). diff --git a/website/google.erb b/website/google.erb index a2fd5cbefdf..8b73b4efe45 100644 --- a/website/google.erb +++ b/website/google.erb @@ -506,6 +506,26 @@ +
  • + Certificate manager + +
  • +
  • Cloud (Stackdriver) Logging