From fb0ff2c536422cdd7f4aa1d3604d712a2485c098 Mon Sep 17 00:00:00 2001 From: The Magician Date: Wed, 17 Mar 2021 08:31:32 -0700 Subject: [PATCH] Added tag product and tagkey resource (#4565) (#3062) * Added tag product and tagkey resource * Skipped vcr tests and added id_format and import_format vcr tests don't work due to randomness * Added self_link definition * Added tag key update test * Re-added id_format and import_format * Marked error code 10 as retryable See https://github.com/googleapis/googleapis/blob/8f117308d5bb55816953a0d6ad1a7d27a69a7d3f/google/rpc/code.proto#L130 * Added additional logging of potentially-retriable errors * Switched to custom import generated imports can't handle slashes in ids * Removed error code 10 from retry errors TLDR if an operation returns error code 10, we can't actually retry the operation itself; we would have to retry the original POST, which would take a larger modification to creating an object * Added mutex for tagkey operations * Removed logging line for manual testing * Run tags resource tests sequentially due to concurrency issues * Switched tagkey mutex to use parent field directly * Made tagkey tests eligible for VCR and non-parallel * Switched to self_link/id_format/import_format using name_from_self_link * Cleaned up docs * Removed etag field * Corrected id/import formats to match self link * Removed custom import Signed-off-by: Modular Magician --- .changelog/4565.txt | 3 + google-beta/config.go | 3 + google-beta/error_retry_predicates_test.go | 29 ++ google-beta/provider.go | 14 +- ...esource_dataflow_flex_template_job_test.go | 2 +- google-beta/resource_tags_tag_key.go | 401 ++++++++++++++++++ .../resource_tags_tag_key_sweeper_test.go | 124 ++++++ google-beta/resource_tags_tag_key_test.go | 155 +++++++ google-beta/tags_operation.go | 76 ++++ website/docs/r/tags_tag_key.html.markdown | 110 +++++ website/google.erb | 16 + 11 files changed, 930 insertions(+), 3 deletions(-) create mode 100644 .changelog/4565.txt create mode 100644 google-beta/resource_tags_tag_key.go create mode 100644 google-beta/resource_tags_tag_key_sweeper_test.go create mode 100644 google-beta/resource_tags_tag_key_test.go create mode 100644 google-beta/tags_operation.go create mode 100644 website/docs/r/tags_tag_key.html.markdown diff --git a/.changelog/4565.txt b/.changelog/4565.txt new file mode 100644 index 0000000000..be9549b17e --- /dev/null +++ b/.changelog/4565.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +`google_tags_tag_key` +``` diff --git a/google-beta/config.go b/google-beta/config.go index f569147692..5b0913e664 100644 --- a/google-beta/config.go +++ b/google-beta/config.go @@ -149,6 +149,7 @@ type Config struct { SpannerBasePath string SQLBasePath string StorageBasePath string + TagsBasePath string TPUBasePath string VPCAccessBasePath string WorkflowsBasePath string @@ -245,6 +246,7 @@ var SourceRepoDefaultBasePath = "https://sourcerepo.googleapis.com/v1/" var SpannerDefaultBasePath = "https://spanner.googleapis.com/v1/" var SQLDefaultBasePath = "https://sqladmin.googleapis.com/sql/v1beta4/" var StorageDefaultBasePath = "https://storage.googleapis.com/storage/v1/" +var TagsDefaultBasePath = "https://cloudresourcemanager.googleapis.com/v3/" var TPUDefaultBasePath = "https://tpu.googleapis.com/v1/" var VPCAccessDefaultBasePath = "https://vpcaccess.googleapis.com/v1beta1/" var WorkflowsDefaultBasePath = "https://workflows.googleapis.com/v1beta/" @@ -1011,6 +1013,7 @@ func ConfigureBasePaths(c *Config) { c.SpannerBasePath = SpannerDefaultBasePath c.SQLBasePath = SQLDefaultBasePath c.StorageBasePath = StorageDefaultBasePath + c.TagsBasePath = TagsDefaultBasePath c.TPUBasePath = TPUDefaultBasePath c.VPCAccessBasePath = VPCAccessDefaultBasePath c.WorkflowsBasePath = WorkflowsDefaultBasePath diff --git a/google-beta/error_retry_predicates_test.go b/google-beta/error_retry_predicates_test.go index e71320ce5c..5806aa0d09 100644 --- a/google-beta/error_retry_predicates_test.go +++ b/google-beta/error_retry_predicates_test.go @@ -1,6 +1,7 @@ package google import ( + "strconv" "testing" "google.golang.org/api/googleapi" @@ -49,3 +50,31 @@ func TestIsAppEngineRetryableError_serverError(t *testing.T) { t.Errorf("Error incorrectly detected as retryable") } } + +func TestIsCommonRetryableErrorCode_retryableErrorCode(t *testing.T) { + codes := []int{429, 500, 502, 503} + for _, code := range codes { + code := code + t.Run(strconv.Itoa(code), func(t *testing.T) { + err := googleapi.Error{ + Code: code, + Body: "some text describing error", + } + isRetryable, _ := isCommonRetryableErrorCode(&err) + if !isRetryable { + t.Errorf("Error not detected as retryable") + } + }) + } +} + +func TestIsCommonRetryableErrorCode_otherError(t *testing.T) { + err := googleapi.Error{ + Code: 404, + Body: "Some unretryable issue", + } + isRetryable, _ := isCommonRetryableErrorCode(&err) + if isRetryable { + t.Errorf("Error incorrectly detected as retryable") + } +} diff --git a/google-beta/provider.go b/google-beta/provider.go index 984904becc..953ac7b13a 100644 --- a/google-beta/provider.go +++ b/google-beta/provider.go @@ -671,6 +671,14 @@ func Provider() *schema.Provider { "GOOGLE_STORAGE_CUSTOM_ENDPOINT", }, StorageDefaultBasePath), }, + "tags_custom_endpoint": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validateCustomEndpoint, + DefaultFunc: schema.MultiEnvDefaultFunc([]string{ + "GOOGLE_TAGS_CUSTOM_ENDPOINT", + }, TagsDefaultBasePath), + }, "tpu_custom_endpoint": { Type: schema.TypeString, Optional: true, @@ -825,9 +833,9 @@ func Provider() *schema.Provider { return provider } -// Generated resources: 214 +// Generated resources: 215 // Generated IAM resources: 108 -// Total generated resources: 322 +// Total generated resources: 323 func ResourceMap() map[string]*schema.Resource { resourceMap, _ := ResourceMapWithErrors() return resourceMap @@ -1155,6 +1163,7 @@ func ResourceMapWithErrors() (map[string]*schema.Resource, error) { "google_storage_object_access_control": resourceStorageObjectAccessControl(), "google_storage_default_object_access_control": resourceStorageDefaultObjectAccessControl(), "google_storage_hmac_key": resourceStorageHmacKey(), + "google_tags_tag_key": resourceTagsTagKey(), "google_tpu_node": resourceTPUNode(), "google_vpc_access_connector": resourceVPCAccessConnector(), "google_workflows_workflow": resourceWorkflowsWorkflow(), @@ -1423,6 +1432,7 @@ func providerConfigure(ctx context.Context, d *schema.ResourceData, p *schema.Pr config.SpannerBasePath = d.Get("spanner_custom_endpoint").(string) config.SQLBasePath = d.Get("sql_custom_endpoint").(string) config.StorageBasePath = d.Get("storage_custom_endpoint").(string) + config.TagsBasePath = d.Get("tags_custom_endpoint").(string) config.TPUBasePath = d.Get("tpu_custom_endpoint").(string) config.VPCAccessBasePath = d.Get("vpc_access_custom_endpoint").(string) config.WorkflowsBasePath = d.Get("workflows_custom_endpoint").(string) diff --git a/google-beta/resource_dataflow_flex_template_job_test.go b/google-beta/resource_dataflow_flex_template_job_test.go index df04d28bb0..0d037482e0 100644 --- a/google-beta/resource_dataflow_flex_template_job_test.go +++ b/google-beta/resource_dataflow_flex_template_job_test.go @@ -8,7 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" - "google.golang.org/api/compute/v1" + compute "google.golang.org/api/compute/v1" ) func TestAccDataflowFlexTemplateJob_basic(t *testing.T) { diff --git a/google-beta/resource_tags_tag_key.go b/google-beta/resource_tags_tag_key.go new file mode 100644 index 0000000000..2d2f5c43cd --- /dev/null +++ b/google-beta/resource_tags_tag_key.go @@ -0,0 +1,401 @@ +// ---------------------------------------------------------------------------- +// +// *** 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" + "strings" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func resourceTagsTagKey() *schema.Resource { + return &schema.Resource{ + Create: resourceTagsTagKeyCreate, + Read: resourceTagsTagKeyRead, + Update: resourceTagsTagKeyUpdate, + Delete: resourceTagsTagKeyDelete, + + Importer: &schema.ResourceImporter{ + State: resourceTagsTagKeyImport, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(4 * time.Minute), + Update: schema.DefaultTimeout(4 * time.Minute), + Delete: schema.DefaultTimeout(4 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "parent": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `Input only. The resource name of the new TagKey's parent. Must be of the form organizations/{org_id}.`, + }, + "short_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `Input only. The user friendly name for a TagKey. The short name should be unique for TagKeys within the same tag namespace. + +The short name must be 1-63 characters, beginning and ending with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between.`, + }, + "description": { + Type: schema.TypeString, + Optional: true, + Description: `User-assigned description of the TagKey. Must not exceed 256 characters.`, + }, + "create_time": { + Type: schema.TypeString, + Computed: true, + Description: `Output only. Creation time. + +A timestamp in RFC3339 UTC "Zulu" format, with nanosecond resolution and up to nine fractional digits. Examples: "2014-10-02T15:01:23Z" and "2014-10-02T15:01:23.045123456Z".`, + }, + "name": { + Type: schema.TypeString, + Computed: true, + Description: `The generated numeric id for the TagKey.`, + }, + "namespaced_name": { + Type: schema.TypeString, + Computed: true, + Description: `Output only. Namespaced name of the TagKey.`, + }, + "update_time": { + Type: schema.TypeString, + Computed: true, + Description: `Output only. Update time. + +A timestamp in RFC3339 UTC "Zulu" format, with nanosecond resolution and up to nine fractional digits. Examples: "2014-10-02T15:01:23Z" and "2014-10-02T15:01:23.045123456Z".`, + }, + }, + UseJSONNumber: true, + } +} + +func resourceTagsTagKeyCreate(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{}) + parentProp, err := expandTagsTagKeyParent(d.Get("parent"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("parent"); !isEmptyValue(reflect.ValueOf(parentProp)) && (ok || !reflect.DeepEqual(v, parentProp)) { + obj["parent"] = parentProp + } + shortNameProp, err := expandTagsTagKeyShortName(d.Get("short_name"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("short_name"); !isEmptyValue(reflect.ValueOf(shortNameProp)) && (ok || !reflect.DeepEqual(v, shortNameProp)) { + obj["shortName"] = shortNameProp + } + descriptionProp, err := expandTagsTagKeyDescription(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 + } + + lockName, err := replaceVars(d, config, "tagKey/{{parent}}") + if err != nil { + return err + } + mutexKV.Lock(lockName) + defer mutexKV.Unlock(lockName) + + url, err := replaceVars(d, config, "{{TagsBasePath}}tagKeys") + if err != nil { + return err + } + + log.Printf("[DEBUG] Creating new TagKey: %#v", obj) + billingProject := "" + + // 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 TagKey: %s", err) + } + + // Store the ID now + id, err := replaceVars(d, config, "tagKeys/{{name}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + // Use the resource in the operation response to populate + // identity fields and d.Id() before read + var opRes map[string]interface{} + err = tagsOperationWaitTimeWithResponse( + config, res, &opRes, "Creating TagKey", userAgent, + d.Timeout(schema.TimeoutCreate)) + if err != nil { + // The resource didn't actually create + d.SetId("") + return fmt.Errorf("Error waiting to create TagKey: %s", err) + } + + if err := d.Set("name", flattenTagsTagKeyName(opRes["name"], d, config)); err != nil { + return err + } + + // This may have caused the ID to update - update it if so. + id, err = replaceVars(d, config, "tagKeys/{{name}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + log.Printf("[DEBUG] Finished creating TagKey %q: %#v", d.Id(), res) + + return resourceTagsTagKeyRead(d, meta) +} + +func resourceTagsTagKeyRead(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, "{{TagsBasePath}}tagKeys/{{name}}") + if err != nil { + return err + } + + billingProject := "" + + // 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("TagsTagKey %q", d.Id())) + } + + if err := d.Set("name", flattenTagsTagKeyName(res["name"], d, config)); err != nil { + return fmt.Errorf("Error reading TagKey: %s", err) + } + if err := d.Set("parent", flattenTagsTagKeyParent(res["parent"], d, config)); err != nil { + return fmt.Errorf("Error reading TagKey: %s", err) + } + if err := d.Set("short_name", flattenTagsTagKeyShortName(res["shortName"], d, config)); err != nil { + return fmt.Errorf("Error reading TagKey: %s", err) + } + if err := d.Set("namespaced_name", flattenTagsTagKeyNamespacedName(res["namespacedName"], d, config)); err != nil { + return fmt.Errorf("Error reading TagKey: %s", err) + } + if err := d.Set("description", flattenTagsTagKeyDescription(res["description"], d, config)); err != nil { + return fmt.Errorf("Error reading TagKey: %s", err) + } + if err := d.Set("create_time", flattenTagsTagKeyCreateTime(res["createTime"], d, config)); err != nil { + return fmt.Errorf("Error reading TagKey: %s", err) + } + if err := d.Set("update_time", flattenTagsTagKeyUpdateTime(res["updateTime"], d, config)); err != nil { + return fmt.Errorf("Error reading TagKey: %s", err) + } + + return nil +} + +func resourceTagsTagKeyUpdate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + userAgent, err := generateUserAgentString(d, config.userAgent) + if err != nil { + return err + } + + billingProject := "" + + obj := make(map[string]interface{}) + descriptionProp, err := expandTagsTagKeyDescription(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 + } + + lockName, err := replaceVars(d, config, "tagKey/{{parent}}") + if err != nil { + return err + } + mutexKV.Lock(lockName) + defer mutexKV.Unlock(lockName) + + url, err := replaceVars(d, config, "{{TagsBasePath}}tagKeys/{{name}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Updating TagKey %q: %#v", d.Id(), obj) + updateMask := []string{} + + if d.HasChange("description") { + updateMask = append(updateMask, "description") + } + // 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 TagKey %q: %s", d.Id(), err) + } else { + log.Printf("[DEBUG] Finished updating TagKey %q: %#v", d.Id(), res) + } + + err = tagsOperationWaitTime( + config, res, "Updating TagKey", userAgent, + d.Timeout(schema.TimeoutUpdate)) + + if err != nil { + return err + } + + return resourceTagsTagKeyRead(d, meta) +} + +func resourceTagsTagKeyDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + userAgent, err := generateUserAgentString(d, config.userAgent) + if err != nil { + return err + } + + billingProject := "" + + lockName, err := replaceVars(d, config, "tagKey/{{parent}}") + if err != nil { + return err + } + mutexKV.Lock(lockName) + defer mutexKV.Unlock(lockName) + + url, err := replaceVars(d, config, "{{TagsBasePath}}tagKeys/{{name}}") + if err != nil { + return err + } + + var obj map[string]interface{} + log.Printf("[DEBUG] Deleting TagKey %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, "TagKey") + } + + err = tagsOperationWaitTime( + config, res, "Deleting TagKey", userAgent, + d.Timeout(schema.TimeoutDelete)) + + if err != nil { + return err + } + + log.Printf("[DEBUG] Finished deleting TagKey %q: %#v", d.Id(), res) + return nil +} + +func resourceTagsTagKeyImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + config := meta.(*Config) + if err := parseImportId([]string{ + "tagKeys/(?P[^/]+)", + "(?P[^/]+)", + }, d, config); err != nil { + return nil, err + } + + // Replace import id for the resource id + id, err := replaceVars(d, config, "tagKeys/{{name}}") + if err != nil { + return nil, fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + return []*schema.ResourceData{d}, nil +} + +func flattenTagsTagKeyName(v interface{}, d *schema.ResourceData, config *Config) interface{} { + if v == nil { + return v + } + return NameFromSelfLinkStateFunc(v) +} + +func flattenTagsTagKeyParent(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenTagsTagKeyShortName(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenTagsTagKeyNamespacedName(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenTagsTagKeyDescription(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenTagsTagKeyCreateTime(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenTagsTagKeyUpdateTime(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func expandTagsTagKeyParent(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func expandTagsTagKeyShortName(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func expandTagsTagKeyDescription(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} diff --git a/google-beta/resource_tags_tag_key_sweeper_test.go b/google-beta/resource_tags_tag_key_sweeper_test.go new file mode 100644 index 0000000000..ad2165ac2d --- /dev/null +++ b/google-beta/resource_tags_tag_key_sweeper_test.go @@ -0,0 +1,124 @@ +// ---------------------------------------------------------------------------- +// +// *** 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" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +func init() { + resource.AddTestSweepers("TagsTagKey", &resource.Sweeper{ + Name: "TagsTagKey", + F: testSweepTagsTagKey, + }) +} + +// At the time of writing, the CI only passes us-central1 as the region +func testSweepTagsTagKey(region string) error { + resourceName := "TagsTagKey" + 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://cloudresourcemanager.googleapis.com/v3/tagKeys", "?")[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["tagKeys"] + 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://cloudresourcemanager.googleapis.com/v3/tagKeys/{{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-beta/resource_tags_tag_key_test.go b/google-beta/resource_tags_tag_key_test.go new file mode 100644 index 0000000000..e98b58a55d --- /dev/null +++ b/google-beta/resource_tags_tag_key_test.go @@ -0,0 +1,155 @@ +package google + +import ( + "fmt" + "strings" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +// Tags tests cannot be run in parallel without running into Error Code 10: ABORTED +// See https://github.com/hashicorp/terraform-provider-google/issues/8637 + +func TestAccTags(t *testing.T) { + testCases := map[string]func(t *testing.T){ + "basic": testAccTagsTagKey_tagKeyBasic, + "update": testAccTagsTagKey_update, + } + + for name, tc := range testCases { + // shadow the tc variable into scope so that when + // the loop continues, if t.Run hasn't executed tc(t) + // yet, we don't have a race condition + // see https://github.com/golang/go/wiki/CommonMistakes#using-goroutines-on-loop-iterator-variables + tc := tc + t.Run(name, func(t *testing.T) { + tc(t) + }) + } +} + +func testAccTagsTagKey_tagKeyBasic(t *testing.T) { + context := map[string]interface{}{ + "org_id": getTestOrgFromEnv(t), + "random_suffix": randString(t, 10), + } + + vcrTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProvidersOiCS, + ExternalProviders: map[string]resource.ExternalProvider{ + "random": {}, + }, + CheckDestroy: testAccCheckTagsTagKeyDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccTagsTagKey_tagKeyBasicExample(context), + }, + }, + }) +} + +func testAccTagsTagKey_tagKeyBasicExample(context map[string]interface{}) string { + return Nprintf(` +resource "google_tags_tag_key" "key" { + provider = google-beta + + parent = "organizations/%{org_id}" + short_name = "foo%{random_suffix}" + description = "For foo%{random_suffix} resources." +} +`, context) +} + +func testAccTagsTagKey_update(t *testing.T) { + context := map[string]interface{}{ + "org_id": getTestOrgFromEnv(t), + "random_suffix": randString(t, 10), + } + + vcrTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProvidersOiCS, + ExternalProviders: map[string]resource.ExternalProvider{ + "random": {}, + }, + CheckDestroy: testAccCheckTagsTagKeyDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccTagsTagKey_basic(context), + }, + { + ResourceName: "google_tags_tag_key.key", + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccTagsTagKey_basicUpdated(context), + }, + { + ResourceName: "google_tags_tag_key.key", + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccTagsTagKey_basic(context map[string]interface{}) string { + return Nprintf(` +resource "google_tags_tag_key" "key" { + provider = google-beta + + parent = "organizations/%{org_id}" + short_name = "foo%{random_suffix}" + description = "For foo%{random_suffix} resources." +} +`, context) +} + +func testAccTagsTagKey_basicUpdated(context map[string]interface{}) string { + return Nprintf(` +resource "google_tags_tag_key" "key" { + provider = google-beta + + parent = "organizations/%{org_id}" + short_name = "foo%{random_suffix}" + description = "Anything related to foo%{random_suffix}" +} +`, context) +} + +func testAccCheckTagsTagKeyDestroyProducer(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_tags_tag_key" { + continue + } + if strings.HasPrefix(name, "data.") { + continue + } + + config := googleProviderConfig(t) + + url, err := replaceVarsForTest(config, rs, "{{TagsBasePath}}{{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("TagsTagKey still exists at %s", url) + } + } + + return nil + } +} diff --git a/google-beta/tags_operation.go b/google-beta/tags_operation.go new file mode 100644 index 0000000000..f2a6390448 --- /dev/null +++ b/google-beta/tags_operation.go @@ -0,0 +1,76 @@ +// ---------------------------------------------------------------------------- +// +// *** 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 ( + "encoding/json" + "fmt" + "time" +) + +type TagsOperationWaiter struct { + Config *Config + UserAgent string + CommonOperationWaiter +} + +func (w *TagsOperationWaiter) 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("https://cloudresourcemanager.googleapis.com/v3/%s", w.CommonOperationWaiter.Op.Name) + + return sendRequest(w.Config, "GET", "", url, w.UserAgent, nil) +} + +func createTagsWaiter(config *Config, op map[string]interface{}, activity, userAgent string) (*TagsOperationWaiter, error) { + if val, ok := op["name"]; !ok || val == "" { + // An operation could also be indicated with a "metadata" field. + if _, ok := op["metadata"]; !ok { + // This was a synchronous call - there is no operation to wait for. + return nil, nil + } + } + w := &TagsOperationWaiter{ + Config: config, + UserAgent: userAgent, + } + if err := w.CommonOperationWaiter.SetOp(op); err != nil { + return nil, err + } + return w, nil +} + +// nolint: deadcode,unused +func tagsOperationWaitTimeWithResponse(config *Config, op map[string]interface{}, response *map[string]interface{}, activity, userAgent string, timeout time.Duration) error { + w, err := createTagsWaiter(config, op, activity, userAgent) + if err != nil || w == nil { + // If w is nil, the op was synchronous. + return err + } + if err := OperationWait(w, activity, timeout, config.PollInterval); err != nil { + return err + } + return json.Unmarshal([]byte(w.CommonOperationWaiter.Op.Response), response) +} + +func tagsOperationWaitTime(config *Config, op map[string]interface{}, activity, userAgent string, timeout time.Duration) error { + w, err := createTagsWaiter(config, op, activity, userAgent) + if err != nil || w == nil { + // If w is nil, the op was synchronous. + return err + } + return OperationWait(w, activity, timeout, config.PollInterval) +} diff --git a/website/docs/r/tags_tag_key.html.markdown b/website/docs/r/tags_tag_key.html.markdown new file mode 100644 index 0000000000..607feec95b --- /dev/null +++ b/website/docs/r/tags_tag_key.html.markdown @@ -0,0 +1,110 @@ +--- +# ---------------------------------------------------------------------------- +# +# *** 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: "Tags" +layout: "google" +page_title: "Google: google_tags_tag_key" +sidebar_current: "docs-google-tags-tag-key" +description: |- + A TagKey, used to group a set of TagValues. +--- + +# google\_tags\_tag\_key + +A TagKey, used to group a set of TagValues. + +~> **Warning:** This resource is in beta, and should be used with the terraform-provider-google-beta provider. +See [Provider Versions](https://terraform.io/docs/providers/google/guides/provider_versions.html) for more details on beta resources. + +To get more information about TagKey, see: + +* [API documentation](https://cloud.google.com/resource-manager/reference/rest/v3/tagKeys) +* How-to Guides + * [Official Documentation](https://cloud.google.com/resource-manager/docs/tags/tags-creating-and-managing) + +## Example Usage - Tag Key Basic + + +```hcl +resource "google_tags_tag_key" "key" { + provider = google-beta + + parent = "organizations/123456789" + short_name = "foo" + description = "For foo resources." +} +``` + +## Argument Reference + +The following arguments are supported: + + +* `parent` - + (Required) + Input only. The resource name of the new TagKey's parent. Must be of the form organizations/{org_id}. + +* `short_name` - + (Required) + Input only. The user friendly name for a TagKey. The short name should be unique for TagKeys within the same tag namespace. + The short name must be 1-63 characters, beginning and ending with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between. + + +- - - + + +* `description` - + (Optional) + User-assigned description of the TagKey. Must not exceed 256 characters. + + +## Attributes Reference + +In addition to the arguments listed above, the following computed attributes are exported: + +* `id` - an identifier for the resource with format `tagKeys/{{name}}` + +* `name` - + The generated numeric id for the TagKey. + +* `namespaced_name` - + Output only. Namespaced name of the TagKey. + +* `create_time` - + Output only. Creation time. + A timestamp in RFC3339 UTC "Zulu" format, with nanosecond resolution and up to nine fractional digits. Examples: "2014-10-02T15:01:23Z" and "2014-10-02T15:01:23.045123456Z". + +* `update_time` - + Output only. Update time. + A timestamp in RFC3339 UTC "Zulu" format, with nanosecond resolution and up to nine fractional digits. Examples: "2014-10-02T15:01:23Z" and "2014-10-02T15:01:23.045123456Z". + + +## Timeouts + +This resource provides the following +[Timeouts](/docs/configuration/resources.html#timeouts) configuration options: + +- `create` - Default is 4 minutes. +- `update` - Default is 4 minutes. +- `delete` - Default is 4 minutes. + +## Import + + +TagKey can be imported using any of these accepted formats: + +``` +$ terraform import google_tags_tag_key.default tagKeys/{{name}} +$ terraform import google_tags_tag_key.default {{name}} +``` diff --git a/website/google.erb b/website/google.erb index 4a299fd05e..269bd1c770 100644 --- a/website/google.erb +++ b/website/google.erb @@ -2833,6 +2833,22 @@ +
  • + Tags + +
  • +
  • Workflows