From 5748a5a76a36fa926efde8e175bed80415cb06ea Mon Sep 17 00:00:00 2001 From: The Magician Date: Fri, 20 Sep 2024 11:34:23 -0700 Subject: [PATCH] Adding a new cloud logging resource `LogScope` to Terraform (#11763) (#8235) [upstream:ec8609a33e02287d6d6d90339938efc55865bc02] Signed-off-by: Modular Magician --- .changelog/11763.txt | 3 + .../provider/provider_mmv1_resources.go | 5 +- .../logging/resource_logging_log_scope.go | 411 ++++++++++++++++++ ...source_logging_log_scope_generated_test.go | 113 +++++ .../resource_logging_log_scope_sweeper.go | 139 ++++++ .../docs/r/logging_log_scope.html.markdown | 121 ++++++ 6 files changed, 790 insertions(+), 2 deletions(-) create mode 100644 .changelog/11763.txt create mode 100644 google-beta/services/logging/resource_logging_log_scope.go create mode 100644 google-beta/services/logging/resource_logging_log_scope_generated_test.go create mode 100644 google-beta/services/logging/resource_logging_log_scope_sweeper.go create mode 100644 website/docs/r/logging_log_scope.html.markdown diff --git a/.changelog/11763.txt b/.changelog/11763.txt new file mode 100644 index 0000000000..459dfede23 --- /dev/null +++ b/.changelog/11763.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +`google_logging_log_scope` +``` \ No newline at end of file diff --git a/google-beta/provider/provider_mmv1_resources.go b/google-beta/provider/provider_mmv1_resources.go index 9e9cf75a32..7bf6d5517e 100644 --- a/google-beta/provider/provider_mmv1_resources.go +++ b/google-beta/provider/provider_mmv1_resources.go @@ -485,9 +485,9 @@ var handwrittenIAMDatasources = map[string]*schema.Resource{ } // Resources -// Generated resources: 529 +// Generated resources: 530 // Generated IAM resources: 291 -// Total generated resources: 820 +// Total generated resources: 821 var generatedResources = map[string]*schema.Resource{ "google_folder_access_approval_settings": accessapproval.ResourceAccessApprovalFolderSettings(), "google_organization_access_approval_settings": accessapproval.ResourceAccessApprovalOrganizationSettings(), @@ -1045,6 +1045,7 @@ var generatedResources = map[string]*schema.Resource{ "google_kms_secret_ciphertext": kms.ResourceKMSSecretCiphertext(), "google_logging_folder_settings": logging.ResourceLoggingFolderSettings(), "google_logging_linked_dataset": logging.ResourceLoggingLinkedDataset(), + "google_logging_log_scope": logging.ResourceLoggingLogScope(), "google_logging_log_view": logging.ResourceLoggingLogView(), "google_logging_log_view_iam_binding": tpgiamresource.ResourceIamBinding(logging.LoggingLogViewIamSchema, logging.LoggingLogViewIamUpdaterProducer, logging.LoggingLogViewIdParseFunc), "google_logging_log_view_iam_member": tpgiamresource.ResourceIamMember(logging.LoggingLogViewIamSchema, logging.LoggingLogViewIamUpdaterProducer, logging.LoggingLogViewIdParseFunc), diff --git a/google-beta/services/logging/resource_logging_log_scope.go b/google-beta/services/logging/resource_logging_log_scope.go new file mode 100644 index 0000000000..02ca198c74 --- /dev/null +++ b/google-beta/services/logging/resource_logging_log_scope.go @@ -0,0 +1,411 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +// ---------------------------------------------------------------------------- +// +// *** 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 logging + +import ( + "fmt" + "log" + "net/http" + "reflect" + "strings" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + + "github.com/hashicorp/terraform-provider-google-beta/google-beta/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google-beta/google-beta/transport" +) + +func ResourceLoggingLogScope() *schema.Resource { + return &schema.Resource{ + Create: resourceLoggingLogScopeCreate, + Read: resourceLoggingLogScopeRead, + Update: resourceLoggingLogScopeUpdate, + Delete: resourceLoggingLogScopeDelete, + + Importer: &schema.ResourceImporter{ + State: resourceLoggingLogScopeImport, + }, + + 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, + DiffSuppressFunc: tpgresource.CompareResourceNames, + Description: `The resource name of the log scope. For example: \'projects/my-project/locations/global/logScopes/my-log-scope\'`, + }, + "resource_names": { + Type: schema.TypeList, + Required: true, + Description: `Names of one or more parent resources : * \'projects/[PROJECT_ID]\' May alternatively be one or more views : * \'projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]\' A log scope can include a maximum of 50 projects and a maximum of 100 resources in total.`, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "description": { + Type: schema.TypeString, + Optional: true, + Description: `Describes this log scopes.`, + }, + "location": { + Type: schema.TypeString, + Computed: true, + Optional: true, + ForceNew: true, + Description: `The location of the resource. The supported locations are: global, us-central1, us-east1, us-west1, asia-east1, europe-west1.`, + }, + "parent": { + Type: schema.TypeString, + Computed: true, + Optional: true, + ForceNew: true, + DiffSuppressFunc: tpgresource.CompareSelfLinkOrResourceName, + Description: `The parent of the resource.`, + }, + "create_time": { + Type: schema.TypeString, + Computed: true, + Description: `Output only. The creation timestamp of the log scopes.`, + }, + "update_time": { + Type: schema.TypeString, + Computed: true, + Description: `Output only. The last update timestamp of the log scopes.`, + }, + }, + UseJSONNumber: true, + } +} + +func resourceLoggingLogScopeCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*transport_tpg.Config) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + if err != nil { + return err + } + + obj := make(map[string]interface{}) + nameProp, err := expandLoggingLogScopeName(d.Get("name"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("name"); !tpgresource.IsEmptyValue(reflect.ValueOf(nameProp)) && (ok || !reflect.DeepEqual(v, nameProp)) { + obj["name"] = nameProp + } + resourceNamesProp, err := expandLoggingLogScopeResourceNames(d.Get("resource_names"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("resource_names"); !tpgresource.IsEmptyValue(reflect.ValueOf(resourceNamesProp)) && (ok || !reflect.DeepEqual(v, resourceNamesProp)) { + obj["resourceNames"] = resourceNamesProp + } + descriptionProp, err := expandLoggingLogScopeDescription(d.Get("description"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("description"); !tpgresource.IsEmptyValue(reflect.ValueOf(descriptionProp)) && (ok || !reflect.DeepEqual(v, descriptionProp)) { + obj["description"] = descriptionProp + } + + obj, err = resourceLoggingLogScopeEncoder(d, meta, obj) + if err != nil { + return err + } + + url, err := tpgresource.ReplaceVars(d, config, "{{LoggingBasePath}}{{parent}}/locations/{{location}}/logScopes?logScopeId={{name}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Creating new LogScope: %#v", obj) + billingProject := "" + + // err == nil indicates that the billing_project value was found + if bp, err := tpgresource.GetBillingProject(d, config); err == nil { + billingProject = bp + } + + headers := make(http.Header) + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: billingProject, + RawURL: url, + UserAgent: userAgent, + Body: obj, + Timeout: d.Timeout(schema.TimeoutCreate), + Headers: headers, + }) + if err != nil { + return fmt.Errorf("Error creating LogScope: %s", err) + } + + // Store the ID now + id, err := tpgresource.ReplaceVars(d, config, "{{parent}}/locations/{{location}}/logScopes/{{name}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + log.Printf("[DEBUG] Finished creating LogScope %q: %#v", d.Id(), res) + + return resourceLoggingLogScopeRead(d, meta) +} + +func resourceLoggingLogScopeRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*transport_tpg.Config) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + if err != nil { + return err + } + + url, err := tpgresource.ReplaceVars(d, config, "{{LoggingBasePath}}{{parent}}/locations/{{location}}/logScopes/{{name}}") + if err != nil { + return err + } + + billingProject := "" + + // err == nil indicates that the billing_project value was found + if bp, err := tpgresource.GetBillingProject(d, config); err == nil { + billingProject = bp + } + + headers := make(http.Header) + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: billingProject, + RawURL: url, + UserAgent: userAgent, + Headers: headers, + }) + if err != nil { + return transport_tpg.HandleNotFoundError(err, d, fmt.Sprintf("LoggingLogScope %q", d.Id())) + } + + if err := d.Set("resource_names", flattenLoggingLogScopeResourceNames(res["resourceNames"], d, config)); err != nil { + return fmt.Errorf("Error reading LogScope: %s", err) + } + if err := d.Set("description", flattenLoggingLogScopeDescription(res["description"], d, config)); err != nil { + return fmt.Errorf("Error reading LogScope: %s", err) + } + if err := d.Set("create_time", flattenLoggingLogScopeCreateTime(res["createTime"], d, config)); err != nil { + return fmt.Errorf("Error reading LogScope: %s", err) + } + if err := d.Set("update_time", flattenLoggingLogScopeUpdateTime(res["updateTime"], d, config)); err != nil { + return fmt.Errorf("Error reading LogScope: %s", err) + } + + return nil +} + +func resourceLoggingLogScopeUpdate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*transport_tpg.Config) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + if err != nil { + return err + } + + billingProject := "" + + obj := make(map[string]interface{}) + resourceNamesProp, err := expandLoggingLogScopeResourceNames(d.Get("resource_names"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("resource_names"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, resourceNamesProp)) { + obj["resourceNames"] = resourceNamesProp + } + descriptionProp, err := expandLoggingLogScopeDescription(d.Get("description"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("description"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, descriptionProp)) { + obj["description"] = descriptionProp + } + + obj, err = resourceLoggingLogScopeEncoder(d, meta, obj) + if err != nil { + return err + } + + url, err := tpgresource.ReplaceVars(d, config, "{{LoggingBasePath}}{{parent}}/locations/{{location}}/logScopes/{{name}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Updating LogScope %q: %#v", d.Id(), obj) + headers := make(http.Header) + updateMask := []string{} + + if d.HasChange("resource_names") { + updateMask = append(updateMask, "resourceNames") + } + + 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 = transport_tpg.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 := tpgresource.GetBillingProject(d, config); err == nil { + billingProject = bp + } + + // if updateMask is empty we are not updating anything so skip the post + if len(updateMask) > 0 { + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "PATCH", + Project: billingProject, + RawURL: url, + UserAgent: userAgent, + Body: obj, + Timeout: d.Timeout(schema.TimeoutUpdate), + Headers: headers, + }) + + if err != nil { + return fmt.Errorf("Error updating LogScope %q: %s", d.Id(), err) + } else { + log.Printf("[DEBUG] Finished updating LogScope %q: %#v", d.Id(), res) + } + + } + + return resourceLoggingLogScopeRead(d, meta) +} + +func resourceLoggingLogScopeDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*transport_tpg.Config) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + if err != nil { + return err + } + + billingProject := "" + + url, err := tpgresource.ReplaceVars(d, config, "{{LoggingBasePath}}{{parent}}/locations/{{location}}/logScopes/{{name}}") + if err != nil { + return err + } + + var obj map[string]interface{} + + // err == nil indicates that the billing_project value was found + if bp, err := tpgresource.GetBillingProject(d, config); err == nil { + billingProject = bp + } + + headers := make(http.Header) + + log.Printf("[DEBUG] Deleting LogScope %q", d.Id()) + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "DELETE", + Project: billingProject, + RawURL: url, + UserAgent: userAgent, + Body: obj, + Timeout: d.Timeout(schema.TimeoutDelete), + Headers: headers, + }) + if err != nil { + return transport_tpg.HandleNotFoundError(err, d, "LogScope") + } + + log.Printf("[DEBUG] Finished deleting LogScope %q: %#v", d.Id(), res) + return nil +} + +func resourceLoggingLogScopeImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + config := meta.(*transport_tpg.Config) + if err := tpgresource.ParseImportId([]string{ + "^(?P.+)/locations/(?P[^/]+)/logScopes/(?P[^/]+)$", + }, d, config); err != nil { + return nil, err + } + + // Replace import id for the resource id + id, err := tpgresource.ReplaceVars(d, config, "{{parent}}/locations/{{location}}/logScopes/{{name}}") + if err != nil { + return nil, fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + return []*schema.ResourceData{d}, nil +} + +func flattenLoggingLogScopeResourceNames(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenLoggingLogScopeDescription(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenLoggingLogScopeCreateTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenLoggingLogScopeUpdateTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func expandLoggingLogScopeName(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandLoggingLogScopeResourceNames(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandLoggingLogScopeDescription(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func resourceLoggingLogScopeEncoder(d *schema.ResourceData, meta interface{}, obj map[string]interface{}) (map[string]interface{}, error) { + // Extract any empty fields from the bucket field. + // Extract parent, location from name + parent := d.Get("parent").(string) + name := d.Get("name").(string) + parent, err := tpgresource.ExtractFieldByPattern("parent", parent, name, "((projects|folders|organizations|billingAccounts)/[a-z0-9A-Z-]*)/locations/.*") + if err != nil { + return nil, fmt.Errorf("error extracting parent field: %s", err) + } + location := d.Get("location").(string) + location, err = tpgresource.ExtractFieldByPattern("location", location, name, "[a-zA-Z]*/[a-z0-9A-Z-]*/locations/([a-z0-9-]*)/logScopes/.*") + if err != nil { + return nil, fmt.Errorf("error extracting location field: %s", err) + } + // Set parent to the extracted value. + d.Set("parent", parent) + // Set all the other fields to their short forms before forming url and setting ID. + name = tpgresource.GetResourceNameFromSelfLink(name) + d.Set("location", location) + d.Set("name", name) + return obj, nil +} diff --git a/google-beta/services/logging/resource_logging_log_scope_generated_test.go b/google-beta/services/logging/resource_logging_log_scope_generated_test.go new file mode 100644 index 0000000000..46f65d0d52 --- /dev/null +++ b/google-beta/services/logging/resource_logging_log_scope_generated_test.go @@ -0,0 +1,113 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +// ---------------------------------------------------------------------------- +// +// *** 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 logging_test + +import ( + "fmt" + "strings" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" + + "github.com/hashicorp/terraform-provider-google-beta/google-beta/acctest" + "github.com/hashicorp/terraform-provider-google-beta/google-beta/envvar" + "github.com/hashicorp/terraform-provider-google-beta/google-beta/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google-beta/google-beta/transport" +) + +func TestAccLoggingLogScope_loggingLogScopeBasicExample(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "project": envvar.GetTestProjectFromEnv(), + "random_suffix": acctest.RandString(t, 10), + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckLoggingLogScopeDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccLoggingLogScope_loggingLogScopeBasicExample(context), + }, + { + ResourceName: "google_logging_log_scope.logging_log_scope", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"location", "name", "parent"}, + }, + }, + }) +} + +func testAccLoggingLogScope_loggingLogScopeBasicExample(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_logging_log_scope" "logging_log_scope" { + parent = "projects/%{project}" + location = "global" + name = "projects/%{project}/locations/global/logScopes/tf-test-my-log-scope%{random_suffix}" + resource_names = [ + "projects/%{project}", + "projects/%{project}/locations/global/buckets/_Default/views/view1%{random_suffix}", + "projects/%{project}/locations/global/buckets/_Default/views/view2%{random_suffix}" + ] + description = "A log scope configured with Terraform" +} +`, context) +} + +func testAccCheckLoggingLogScopeDestroyProducer(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_logging_log_scope" { + continue + } + if strings.HasPrefix(name, "data.") { + continue + } + + config := acctest.GoogleProviderConfig(t) + + url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{LoggingBasePath}}{{parent}}/locations/{{location}}/logScopes/{{name}}") + if err != nil { + return err + } + + billingProject := "" + + if config.BillingProject != "" { + billingProject = config.BillingProject + } + + _, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: billingProject, + RawURL: url, + UserAgent: config.UserAgent, + }) + if err == nil { + return fmt.Errorf("LoggingLogScope still exists at %s", url) + } + } + + return nil + } +} diff --git a/google-beta/services/logging/resource_logging_log_scope_sweeper.go b/google-beta/services/logging/resource_logging_log_scope_sweeper.go new file mode 100644 index 0000000000..26f123b023 --- /dev/null +++ b/google-beta/services/logging/resource_logging_log_scope_sweeper.go @@ -0,0 +1,139 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +// ---------------------------------------------------------------------------- +// +// *** 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 logging + +import ( + "context" + "log" + "strings" + "testing" + + "github.com/hashicorp/terraform-provider-google-beta/google-beta/envvar" + "github.com/hashicorp/terraform-provider-google-beta/google-beta/sweeper" + "github.com/hashicorp/terraform-provider-google-beta/google-beta/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google-beta/google-beta/transport" +) + +func init() { + sweeper.AddTestSweepers("LoggingLogScope", testSweepLoggingLogScope) +} + +// At the time of writing, the CI only passes us-central1 as the region +func testSweepLoggingLogScope(region string) error { + resourceName := "LoggingLogScope" + log.Printf("[INFO][SWEEPER_LOG] Starting sweeper for %s", resourceName) + + config, err := sweeper.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 := envvar.GetTestBillingAccountFromEnv(t) + + // Setup variables to replace in list template + d := &tpgresource.ResourceDataMock{ + FieldsInSchema: map[string]interface{}{ + "project": config.Project, + "region": region, + "location": region, + "zone": "-", + "billing_account": billingId, + }, + } + + listTemplate := strings.Split("https://logging.googleapis.com/v2/{{parent}}/locations/{{location}}/logScopes", "?")[0] + listUrl, err := tpgresource.ReplaceVars(d, config, listTemplate) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] error preparing sweeper list url: %s", err) + return nil + } + + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: config.Project, + RawURL: listUrl, + UserAgent: config.UserAgent, + }) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] Error in response from request %s: %s", listUrl, err) + return nil + } + + resourceList, ok := res["logScopes"] + 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 := tpgresource.GetResourceNameFromSelfLink(obj["name"].(string)) + // Skip resources that shouldn't be sweeped + if !sweeper.IsSweepableTestResource(name) { + nonPrefixCount++ + continue + } + + deleteTemplate := "https://logging.googleapis.com/v2/{{parent}}/locations/{{location}}/logScopes/{{name}}" + deleteUrl, err := tpgresource.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 = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "DELETE", + Project: config.Project, + RawURL: deleteUrl, + UserAgent: config.UserAgent, + }) + 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/website/docs/r/logging_log_scope.html.markdown b/website/docs/r/logging_log_scope.html.markdown new file mode 100644 index 0000000000..1cb58ec5f8 --- /dev/null +++ b/website/docs/r/logging_log_scope.html.markdown @@ -0,0 +1,121 @@ +--- +# ---------------------------------------------------------------------------- +# +# *** 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: "Cloud (Stackdriver) Logging" +description: |- + Describes a group of resources to read log entries from +--- + +# google_logging_log_scope + +Describes a group of resources to read log entries from + + +To get more information about LogScope, see: + +* [API documentation](https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.locations.logScopes) +* How-to Guides + * [Official Documentation](https://cloud.google.com/logging/docs/apis) + +## Example Usage - Logging Log Scope Basic + + +```hcl +resource "google_logging_log_scope" "logging_log_scope" { + parent = "projects/my-project-name" + location = "global" + name = "projects/my-project-name/locations/global/logScopes/my-log-scope" + resource_names = [ + "projects/my-project-name", + "projects/my-project-name/locations/global/buckets/_Default/views/view1", + "projects/my-project-name/locations/global/buckets/_Default/views/view2" + ] + description = "A log scope configured with Terraform" +} +``` + +## Argument Reference + +The following arguments are supported: + + +* `name` - + (Required) + The resource name of the log scope. For example: \`projects/my-project/locations/global/logScopes/my-log-scope\` + +* `resource_names` - + (Required) + Names of one or more parent resources : * \`projects/[PROJECT_ID]\` May alternatively be one or more views : * \`projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]\` A log scope can include a maximum of 50 projects and a maximum of 100 resources in total. + + +- - - + + +* `description` - + (Optional) + Describes this log scopes. + +* `parent` - + (Optional) + The parent of the resource. + +* `location` - + (Optional) + The location of the resource. The supported locations are: global, us-central1, us-east1, us-west1, asia-east1, europe-west1. + + +## Attributes Reference + +In addition to the arguments listed above, the following computed attributes are exported: + +* `id` - an identifier for the resource with format `{{parent}}/locations/{{location}}/logScopes/{{name}}` + +* `create_time` - + Output only. The creation timestamp of the log scopes. + +* `update_time` - + Output only. The last update timestamp of the log scopes. + + +## Timeouts + +This resource provides the following +[Timeouts](https://developer.hashicorp.com/terraform/plugin/sdkv2/resources/retries-and-customizable-timeouts) configuration options: + +- `create` - Default is 20 minutes. +- `update` - Default is 20 minutes. +- `delete` - Default is 20 minutes. + +## Import + + +LogScope can be imported using any of these accepted formats: + +* `{{parent}}/locations/{{location}}/logScopes/{{name}}` + + +In Terraform v1.5.0 and later, use an [`import` block](https://developer.hashicorp.com/terraform/language/import) to import LogScope using one of the formats above. For example: + +```tf +import { + id = "{{parent}}/locations/{{location}}/logScopes/{{name}}" + to = google_logging_log_scope.default +} +``` + +When using the [`terraform import` command](https://developer.hashicorp.com/terraform/cli/commands/import), LogScope can be imported using one of the formats above. For example: + +``` +$ terraform import google_logging_log_scope.default {{parent}}/locations/{{location}}/logScopes/{{name}} +```