diff --git a/.changelog/6716.txt b/.changelog/6716.txt new file mode 100644 index 0000000000..27f06e0863 --- /dev/null +++ b/.changelog/6716.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +`google_tags_location_tag_bindings` +``` diff --git a/google-beta/config.go b/google-beta/config.go index 06f08daf6c..5cb492ea7f 100644 --- a/google-beta/config.go +++ b/google-beta/config.go @@ -278,6 +278,7 @@ type Config struct { CloudIoTBasePath string ServiceNetworkingBasePath string BigtableAdminBasePath string + TagsLocationBasePath string // dcl ContainerAwsBasePath string @@ -393,6 +394,7 @@ const ServiceNetworkingBasePathKey = "ServiceNetworking" const BigtableAdminBasePathKey = "BigtableAdmin" const ContainerAwsBasePathKey = "ContainerAws" const ContainerAzureBasePathKey = "ContainerAzure" +const TagsLocationBasePathKey = "TagsLocation" // Generated product base paths var DefaultBasePaths = map[string]string{ @@ -502,6 +504,7 @@ var DefaultBasePaths = map[string]string{ BigtableAdminBasePathKey: "https://bigtableadmin.googleapis.com/v2/", ContainerAwsBasePathKey: "https://{{location}}-gkemulticloud.googleapis.com/v1/", ContainerAzureBasePathKey: "https://{{location}}-gkemulticloud.googleapis.com/v1/", + TagsLocationBasePathKey: "https://{{location}}-cloudresourcemanager.googleapis.com/v3/", } var DefaultClientScopes = []string{ @@ -1389,4 +1392,5 @@ func ConfigureBasePaths(c *Config) { c.ServiceNetworkingBasePath = DefaultBasePaths[ServiceNetworkingBasePathKey] c.BigQueryBasePath = DefaultBasePaths[BigQueryBasePathKey] c.BigtableAdminBasePath = DefaultBasePaths[BigtableAdminBasePathKey] + c.TagsLocationBasePath = DefaultBasePaths[TagsLocationBasePathKey] } diff --git a/google-beta/provider.go b/google-beta/provider.go index 828ec98bf6..6f739200f9 100644 --- a/google-beta/provider.go +++ b/google-beta/provider.go @@ -922,6 +922,7 @@ func Provider() *schema.Provider { ServiceNetworkingCustomEndpointEntryKey: ServiceNetworkingCustomEndpointEntry, ServiceUsageCustomEndpointEntryKey: ServiceUsageCustomEndpointEntry, BigtableAdminCustomEndpointEntryKey: BigtableAdminCustomEndpointEntry, + TagsLocationCustomEndpointEntryKey: TagsLocationCustomEndpointEntry, // dcl ContainerAwsCustomEndpointEntryKey: ContainerAwsCustomEndpointEntry, @@ -1674,6 +1675,7 @@ func ResourceMapWithErrors() (map[string]*schema.Resource, error) { "google_storage_default_object_acl": resourceStorageDefaultObjectAcl(), "google_storage_notification": resourceStorageNotification(), "google_storage_transfer_job": resourceStorageTransferJob(), + "google_tags_location_tag_binding": resourceTagsLocationTagBinding(), // ####### END handwritten resources ########### }, map[string]*schema.Resource{ @@ -1933,6 +1935,7 @@ func providerConfigure(ctx context.Context, d *schema.ResourceData, p *schema.Pr config.ServiceNetworkingBasePath = d.Get(ServiceNetworkingCustomEndpointEntryKey).(string) config.ServiceUsageBasePath = d.Get(ServiceUsageCustomEndpointEntryKey).(string) config.BigtableAdminBasePath = d.Get(BigtableAdminCustomEndpointEntryKey).(string) + config.TagsLocationBasePath = d.Get(TagsLocationCustomEndpointEntryKey).(string) // dcl config.ContainerAwsBasePath = d.Get(ContainerAwsCustomEndpointEntryKey).(string) diff --git a/google-beta/provider_handwritten_endpoint.go b/google-beta/provider_handwritten_endpoint.go index ddc40c1748..041e3664bb 100644 --- a/google-beta/provider_handwritten_endpoint.go +++ b/google-beta/provider_handwritten_endpoint.go @@ -148,6 +148,16 @@ var ContainerAzureCustomEndpointEntry = &schema.Schema{ }, DefaultBasePaths[ContainerAzureBasePathKey]), } +var TagsLocationCustomEndpointEntryKey = "tags_location_custom_endpoint" +var TagsLocationCustomEndpointEntry = &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ValidateFunc: validateCustomEndpoint, + DefaultFunc: schema.MultiEnvDefaultFunc([]string{ + "GOOGLE_TAGS_LOCATION_CUSTOM_ENDPOINT", + }, DefaultBasePaths[TagsLocationBasePathKey]), +} + func validateCustomEndpoint(v interface{}, k string) (ws []string, errors []error) { re := `.*/[^/]+/$` return validateRegexp(re)(v, k) diff --git a/google-beta/resource_tags_location_tag_bindings.go b/google-beta/resource_tags_location_tag_bindings.go new file mode 100644 index 0000000000..47e050710c --- /dev/null +++ b/google-beta/resource_tags_location_tag_bindings.go @@ -0,0 +1,343 @@ +package google + +import ( + "fmt" + "log" + "reflect" + "strings" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func resourceTagsLocationTagBinding() *schema.Resource { + return &schema.Resource{ + Create: resourceTagsLocationTagBindingCreate, + Read: resourceTagsLocationTagBindingRead, + Delete: resourceTagsLocationTagBindingDelete, + + Importer: &schema.ResourceImporter{ + State: resourceTagsLocationTagBindingImport, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(20 * time.Minute), + Delete: schema.DefaultTimeout(20 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "parent": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `The full resource name of the resource the TagValue is bound to. E.g. //cloudresourcemanager.googleapis.com/projects/123`, + }, + "tag_value": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `The TagValue of the TagBinding. Must be of the form tagValues/456.`, + }, + "location": { + Type: schema.TypeString, + ForceNew: true, + Optional: true, + Description: `The geographic location where the transfer config should reside. +Examples: US, EU, asia-northeast1. The default value is US.`, + }, + "name": { + Type: schema.TypeString, + Computed: true, + Description: `The generated id for the TagBinding. This is a string of the form: 'tagBindings/{full-resource-name}/{tag-value-name}'`, + }, + }, + UseJSONNumber: true, + } +} + +func resourceTagsLocationTagBindingCreate(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 := expandNestedTagsLocationTagBindingParent(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 + } + tagValueProp, err := expandNestedTagsLocationTagBindingTagValue(d.Get("tag_value"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("tag_value"); !isEmptyValue(reflect.ValueOf(tagValueProp)) && (ok || !reflect.DeepEqual(v, tagValueProp)) { + obj["tagValue"] = tagValueProp + } + + url, err := replaceVars(d, config, "{{TagsLocationBasePath}}tagBindings") + log.Printf("url for TagsLocation: %s", url) + if err != nil { + return err + } + + log.Printf("[DEBUG] Creating new LocationTagBinding: %#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 LocationTagBinding: %s", err) + } + + // 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 LocationTagBinding", userAgent, + d.Timeout(schema.TimeoutCreate)) + + if err != nil { + d.SetId("") + return fmt.Errorf("Error waiting to create LocationTagBinding: %s", err) + } + + if _, ok := opRes["tagBindings"]; ok { + opRes, err = flattenNestedTagsLocationTagBinding(d, meta, opRes) + if err != nil { + return fmt.Errorf("Error getting nested object from operation response: %s", err) + } + if opRes == nil { + // Object isn't there any more - remove it from the state. + d.SetId("") + return fmt.Errorf("Error decoding response from operation, could not find nested object") + } + } + if err := d.Set("name", flattenNestedTagsLocationTagBindingName(opRes["name"], d, config)); err != nil { + return err + } + + id, err := replaceVars(d, config, "{{location}}/{{name}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + log.Printf("[DEBUG] Finished creating LocationTagBinding %q: %#v", d.Id(), res) + + return resourceTagsLocationTagBindingRead(d, meta) +} + +func resourceTagsLocationTagBindingRead(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, "{{TagsLocationBasePath}}tagBindings/?parent={{parent}}&pageSize=300") + 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("TagsLocationTagBinding %q", d.Id())) + } + log.Printf("[DEBUG] Skipping res with name for import = %#v,)", res) + + p, ok := res["tagBindings"] + if !ok || p == nil { + return nil + } + pView := p.([]interface{}) + + //if there are more than 300 bindings - handling pagination over here + if pageToken, ok := res["nextPageToken"].(string); ok { + for pageToken != "" { + url, err = addQueryParams(url, map[string]string{"pageToken": fmt.Sprintf("%s", res["nextPageToken"])}) + if err != nil { + return handleNotFoundError(err, d, fmt.Sprintf("TagsLocationTagBinding %q", d.Id())) + } + resp, err := sendRequest(config, "GET", billingProject, url, userAgent, nil) + if err != nil { + return handleNotFoundError(err, d, fmt.Sprintf("TagsLocationTagBinding %q", d.Id())) + } + if resp == nil { + d.SetId("") + return nil + } + v, ok := resp["tagBindings"] + if !ok || v == nil { + return nil + } + pView = append(pView, v.([]interface{})...) + if token, ok := res["nextPageToken"]; ok { + pageToken = token.(string) + } else { + pageToken = "" + } + } + } + + newMap := make(map[string]interface{}, 1) + newMap["tagBindings"] = pView + + res, err = flattenNestedTagsLocationTagBinding(d, meta, newMap) + if err != nil { + return err + } + + if err := d.Set("name", flattenNestedTagsLocationTagBindingName(res["name"], d, config)); err != nil { + return fmt.Errorf("Error reading LocationTagBinding: %s", err) + } + if err := d.Set("parent", flattenNestedTagsLocationTagBindingParent(res["parent"], d, config)); err != nil { + return fmt.Errorf("Error reading LocationTagBinding: %s", err) + } + if err := d.Set("tag_value", flattenNestedTagsLocationTagBindingTagValue(res["tagValue"], d, config)); err != nil { + return fmt.Errorf("Error reading LocationTagBinding: %s", err) + } + + return nil +} + +func resourceTagsLocationTagBindingDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + userAgent, err := generateUserAgentString(d, config.userAgent) + if err != nil { + return err + } + + billingProject := "" + + url, err := replaceVars(d, config, "{{TagsLocationBasePath}}{{name}}") + if err != nil { + return err + } + + var obj map[string]interface{} + log.Printf("[DEBUG] Deleting LocationTagBinding %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, "LocationTagBinding") + } + + err = tagsOperationWaitTime( + config, res, "Deleting LocationTagBinding", userAgent, + d.Timeout(schema.TimeoutDelete)) + + if err != nil { + return err + } + + log.Printf("[DEBUG] Finished deleting LocationTagBinding %q: %#v", d.Id(), res) + return nil +} + +func resourceTagsLocationTagBindingImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + config := meta.(*Config) + if err := parseImportId([]string{"(?P[^/]+)/tagBindings/(?P[^/]+)/tagValues/(?P[^/]+)"}, d, config); err != nil { + return nil, err + } + + parent := d.Get("parent").(string) + parentProper := strings.ReplaceAll(parent, "%2F", "/") + d.Set("parent", parentProper) + d.Set("name", fmt.Sprintf("tagBindings/%s/tagValues/%s", parent, d.Get("tag_value").(string))) + id, err := replaceVars(d, config, "{{location}}/{{name}}") + if err != nil { + return nil, fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + return []*schema.ResourceData{d}, nil +} + +func flattenNestedTagsLocationTagBindingName(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenNestedTagsLocationTagBindingParent(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenNestedTagsLocationTagBindingTagValue(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func expandNestedTagsLocationTagBindingParent(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func expandNestedTagsLocationTagBindingTagValue(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + return v, nil +} + +func flattenNestedTagsLocationTagBinding(d *schema.ResourceData, meta interface{}, res map[string]interface{}) (map[string]interface{}, error) { + var v interface{} + var ok bool + + v, ok = res["tagBindings"] + if !ok || v == nil { + return nil, nil + } + + switch v.(type) { + case []interface{}: + log.Printf("[DEBUG] Hey it's in break = %#v,)", v) + break + case map[string]interface{}: + // Construct list out of single nested resource + v = []interface{}{v} + default: + return nil, fmt.Errorf("expected list or map for value tagBindings. Actual value: %v", v) + } + + _, item, err := resourceTagsLocationTagBindingFindNestedObjectInList(d, meta, v.([]interface{})) + if err != nil { + return nil, err + } + return item, nil +} + +func resourceTagsLocationTagBindingFindNestedObjectInList(d *schema.ResourceData, meta interface{}, items []interface{}) (index int, item map[string]interface{}, err error) { + expectedName := d.Get("name") + expectedFlattenedName := flattenNestedTagsLocationTagBindingName(expectedName, d, meta.(*Config)) + + // Search list for this resource. + for idx, itemRaw := range items { + if itemRaw == nil { + continue + } + + item := itemRaw.(map[string]interface{}) + itemName := flattenNestedTagsLocationTagBindingName(item["name"], d, meta.(*Config)) + // isEmptyValue check so that if one is nil and the other is "", that's considered a match + if !(isEmptyValue(reflect.ValueOf(itemName)) && isEmptyValue(reflect.ValueOf(expectedFlattenedName))) && !reflect.DeepEqual(itemName, expectedFlattenedName) { + log.Printf("[DEBUG] Skipping item with name= %#v, looking for %#v)", itemName, expectedFlattenedName) + continue + } + return idx, item, nil + } + return -1, nil, nil +} diff --git a/google-beta/resource_tags_tag_value.go b/google-beta/resource_tags_tag_value.go index 846d7f14e7..3fdc1cb8c1 100644 --- a/google-beta/resource_tags_tag_value.go +++ b/google-beta/resource_tags_tag_value.go @@ -85,7 +85,6 @@ A timestamp in RFC3339 UTC "Zulu" format, with nanosecond resolution and up to n 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".`, }, }, diff --git a/google-beta/resource_tags_test.go b/google-beta/resource_tags_test.go index cfa2e290dd..8a18575dea 100644 --- a/google-beta/resource_tags_test.go +++ b/google-beta/resource_tags_test.go @@ -26,6 +26,7 @@ func TestAccTags(t *testing.T) { "tagValueIamBinding": testAccTagsTagValueIamBinding, "tagValueIamMember": testAccTagsTagValueIamMember, "tagValueIamPolicy": testAccTagsTagValueIamPolicy, + "tagsLocationTagBindingBasic": testAccTagsLocationTagBinding_locationTagBindingbasic, } for name, tc := range testCases { @@ -774,3 +775,107 @@ resource "google_tags_tag_value_iam_binding" "foo" { } `, context) } + +func testAccTagsLocationTagBinding_locationTagBindingbasic(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + // "org_id": getTestOrgFromEnv(t), + // "project_id": "tf-test-" + randString(t, 10), + "random_suffix": randString(t, 10), + } + + vcrTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + ExternalProviders: map[string]resource.ExternalProvider{ + "random": {}, + }, + CheckDestroy: testAccCheckTagsLocationTagBindingDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccTagsLocationTagBinding_locationTagBindingBasicExample(context), + }, + { + ResourceName: "google_tags_location_tag_binding.binding", + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccTagsLocationTagBinding_locationTagBindingBasicExample(context map[string]interface{}) string { + return Nprintf(` +data "google_project" "project" { +} + +resource "google_tags_tag_key" "key" { + parent = "organizations/${data.google_project.project.org_id}" + short_name = "keyname%{random_suffix}" + description = "For a certain set of resources." +} + +resource "google_tags_tag_value" "value" { + parent = "tagKeys/${google_tags_tag_key.key.name}" + short_name = "foo%{random_suffix}" + description = "For foo%{random_suffix} resources." +} + +resource "google_cloud_run_service" "default" { + name = "tf-test-cloudrun-srv%{random_suffix}" + location = "us-central1" + + template { + spec { + containers { + image = "us-docker.pkg.dev/cloudrun/container/hello" + } + } + } + + traffic { + percent = 100 + latest_revision = true + } +} + +resource "google_tags_location_tag_binding" "binding" { + parent = "//run.googleapis.com/projects/${data.google_project.project.number}/locations/${google_cloud_run_service.default.location}/services/${google_cloud_run_service.default.name}" + tag_value = "tagValues/${google_tags_tag_value.value.name}" + location = "us-central1" +} +`, context) +} + +func testAccCheckTagsLocationTagBindingDestroyProducer(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_location_tag_binding" { + continue + } + if strings.HasPrefix(name, "data.") { + continue + } + + config := googleProviderConfig(t) + + url, err := replaceVarsForTest(config, rs, "{{TagsLocationBasePath}}{{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("TagsTagBinding still exists at %s", url) + } + } + return nil + } +} diff --git a/website/docs/r/google_tags_location_tag_binding.html.markdown b/website/docs/r/google_tags_location_tag_binding.html.markdown new file mode 100644 index 0000000000..9c51e15c1d --- /dev/null +++ b/website/docs/r/google_tags_location_tag_binding.html.markdown @@ -0,0 +1,93 @@ +subcategory: "Tags" +page_title: "Google: google_tags_location_tag_binding" +description: |- + A LocationTagBinding represents a connection between a TagValue and a Regional cloud resources. +--- + +# google\_tags\_location\_tag\_binding + +A TagBinding represents a connection between a TagValue and a Regional cloud resource (currently project, folder, or organization). Once a TagBinding is created, the TagValue is applied to all the descendants of the cloud resource. + + +To get more information about TagBinding, see: + +* [API documentation](https://cloud.google.com/resource-manager/reference/rest/v3/tagBindings) +* How-to Guides + * [Official Documentation](https://cloud.google.com/resource-manager/docs/tags/tags-creating-and-managing) + +## Example Usage - Location Tag Binding Basic + + +```hcl +resource "google_project" "project" { + project_id = "project_id" + name = "project_id" + org_id = "123456789" +} + +resource "google_tags_tag_key" "key" { + parent = "organizations/123456789" + short_name = "keyname" + description = "For keyname resources." +} + +resource "google_tags_tag_value" "value" { + parent = "tagKeys/${google_tags_tag_key.key.name}" + short_name = "valuename" + description = "For valuename resources." +} + +resource "google_tags_location_tag_binding" "binding" { + parent = "//run.googleapis.com/projects/${data.google_project.project.number}/locations/${google_cloud_run_service.default.location}/services/${google_cloud_run_service.default.name}" + tag_value = "tagValues/${google_tags_tag_value.value.name}" + location = "us-central1" +} +``` + +## Argument Reference + +The following arguments are supported: + + +* `parent` - + (Required) + The full resource name of the resource the TagValue is bound to. E.g. //cloudresourcemanager.googleapis.com/projects/123 + +* `tag_value` - + (Required) + The TagValue of the TagBinding. Must be of the form tagValues/456. + +* `location` - + (Required) + Location of the resource. + +- - - + + + +## Attributes Reference + +In addition to the arguments listed above, the following computed attributes are exported: + +* `id` - an identifier for the resource with format `{{location}}/{{name}}` + +* `name` - + The generated id for the TagBinding. This is a string of the form: `tagBindings/{parent}/{tag-value-name}` + + +## Timeouts + +This resource provides the following +[Timeouts](/docs/configuration/resources.html#timeouts) configuration options: + +- `create` - Default is 20 minutes. +- `delete` - Default is 20 minutes. + +## Import + + +TagBinding can be imported using any of these accepted formats: + +``` +$ terraform import google_tags_location_tag_binding.default {{location}}/{{name}} +```