From da99b0b12a9a701953310f70f2e5cc89cc07c27e Mon Sep 17 00:00:00 2001 From: Modular Magician Date: Mon, 6 Jan 2025 20:18:50 +0000 Subject: [PATCH] Add google_chronicle_data_access_label resource to chronicle (#12638) [upstream:f277e787b392fec4b67c384626ac0bab0808c3b1] Signed-off-by: Modular Magician --- .changelog/12638.txt | 3 + .../provider/provider_mmv1_resources.go | 5 +- .../resource_chronicle_data_access_label.go | 458 ++++++++++++++++++ ...icle_data_access_label_generated_meta.yaml | 5 + ...onicle_data_access_label_generated_test.go | 110 +++++ ...rce_chronicle_data_access_label_sweeper.go | 143 ++++++ ...source_chronicle_data_access_label_test.go | 74 +++ .../chronicle_data_access_label.html.markdown | 148 ++++++ 8 files changed, 944 insertions(+), 2 deletions(-) create mode 100644 .changelog/12638.txt create mode 100644 google-beta/services/chronicle/resource_chronicle_data_access_label.go create mode 100644 google-beta/services/chronicle/resource_chronicle_data_access_label_generated_meta.yaml create mode 100644 google-beta/services/chronicle/resource_chronicle_data_access_label_generated_test.go create mode 100644 google-beta/services/chronicle/resource_chronicle_data_access_label_sweeper.go create mode 100644 google-beta/services/chronicle/resource_chronicle_data_access_label_test.go create mode 100644 website/docs/r/chronicle_data_access_label.html.markdown diff --git a/.changelog/12638.txt b/.changelog/12638.txt new file mode 100644 index 0000000000..152a3c7cda --- /dev/null +++ b/.changelog/12638.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +`google_chronicle_data_access_label` +``` \ 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 bb1afa71d7..171bf836d9 100644 --- a/google-beta/provider/provider_mmv1_resources.go +++ b/google-beta/provider/provider_mmv1_resources.go @@ -513,9 +513,9 @@ var handwrittenIAMDatasources = map[string]*schema.Resource{ } // Resources -// Generated resources: 574 +// Generated resources: 575 // Generated IAM resources: 294 -// Total generated resources: 868 +// Total generated resources: 869 var generatedResources = map[string]*schema.Resource{ "google_folder_access_approval_settings": accessapproval.ResourceAccessApprovalFolderSettings(), "google_organization_access_approval_settings": accessapproval.ResourceAccessApprovalOrganizationSettings(), @@ -647,6 +647,7 @@ var generatedResources = map[string]*schema.Resource{ "google_certificate_manager_certificate_map_entry": certificatemanager.ResourceCertificateManagerCertificateMapEntry(), "google_certificate_manager_dns_authorization": certificatemanager.ResourceCertificateManagerDnsAuthorization(), "google_certificate_manager_trust_config": certificatemanager.ResourceCertificateManagerTrustConfig(), + "google_chronicle_data_access_label": chronicle.ResourceChronicleDataAccessLabel(), "google_chronicle_watchlist": chronicle.ResourceChronicleWatchlist(), "google_cloud_asset_folder_feed": cloudasset.ResourceCloudAssetFolderFeed(), "google_cloud_asset_organization_feed": cloudasset.ResourceCloudAssetOrganizationFeed(), diff --git a/google-beta/services/chronicle/resource_chronicle_data_access_label.go b/google-beta/services/chronicle/resource_chronicle_data_access_label.go new file mode 100644 index 0000000000..3108eb05b2 --- /dev/null +++ b/google-beta/services/chronicle/resource_chronicle_data_access_label.go @@ -0,0 +1,458 @@ +// 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 chronicle + +import ( + "fmt" + "log" + "net/http" + "reflect" + "strings" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" + "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 ResourceChronicleDataAccessLabel() *schema.Resource { + return &schema.Resource{ + Create: resourceChronicleDataAccessLabelCreate, + Read: resourceChronicleDataAccessLabelRead, + Update: resourceChronicleDataAccessLabelUpdate, + Delete: resourceChronicleDataAccessLabelDelete, + + Importer: &schema.ResourceImporter{ + State: resourceChronicleDataAccessLabelImport, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(20 * time.Minute), + Update: schema.DefaultTimeout(20 * time.Minute), + Delete: schema.DefaultTimeout(20 * time.Minute), + }, + + CustomizeDiff: customdiff.All( + tpgresource.DefaultProviderProject, + ), + + Schema: map[string]*schema.Schema{ + "data_access_label_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `Required. The ID to use for the data access label, which will become the label's +display name and the final component of the label's resource name. It must +only contain ASCII lowercase letters, numbers, and dashes; it must begin +with a letter, and it must not exceed 1000 characters.`, + }, + "instance": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `The unique identifier for the Chronicle instance, which is the same as the customer ID.`, + }, + "location": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `The location of the resource. This is the geographical region where the Chronicle instance resides, such as "us" or "europe-west2".`, + }, + "udm_query": { + Type: schema.TypeString, + Required: true, + Description: `A UDM query over event data.`, + }, + "description": { + Type: schema.TypeString, + Optional: true, + Description: `Optional. A description of the data access label for a human reader.`, + }, + "author": { + Type: schema.TypeString, + Computed: true, + Description: `Output only. The user who created the data access label.`, + }, + "create_time": { + Type: schema.TypeString, + Computed: true, + Description: `Output only. The time at which the data access label was created.`, + }, + "display_name": { + Type: schema.TypeString, + Computed: true, + Description: `Output only. The short name displayed for the label as it appears on event data. This is same as data access label id.`, + }, + "last_editor": { + Type: schema.TypeString, + Computed: true, + Description: `Output only. The user who last updated the data access label.`, + }, + "name": { + Type: schema.TypeString, + Computed: true, + Description: `The unique resource name of the data access label. This unique identifier is generated using values provided for the URL parameters. +Format: +projects/{project}/locations/{location}/instances/{instance}/dataAccessLabels/{data_access_label_id}`, + }, + "update_time": { + Type: schema.TypeString, + Computed: true, + Description: `Output only. The time at which the data access label was last updated.`, + }, + "project": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, + }, + UseJSONNumber: true, + } +} + +func resourceChronicleDataAccessLabelCreate(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{}) + descriptionProp, err := expandChronicleDataAccessLabelDescription(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 + } + udmQueryProp, err := expandChronicleDataAccessLabelUdmQuery(d.Get("udm_query"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("udm_query"); !tpgresource.IsEmptyValue(reflect.ValueOf(udmQueryProp)) && (ok || !reflect.DeepEqual(v, udmQueryProp)) { + obj["udmQuery"] = udmQueryProp + } + + url, err := tpgresource.ReplaceVars(d, config, "{{ChronicleBasePath}}projects/{{project}}/locations/{{location}}/instances/{{instance}}/dataAccessLabels?dataAccessLabelId={{data_access_label_id}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Creating new DataAccessLabel: %#v", obj) + billingProject := "" + + project, err := tpgresource.GetProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for DataAccessLabel: %s", err) + } + billingProject = project + + // 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 DataAccessLabel: %s", err) + } + if err := d.Set("name", flattenChronicleDataAccessLabelName(res["name"], d, config)); err != nil { + return fmt.Errorf(`Error setting computed identity field "name": %s`, err) + } + + // Store the ID now + id, err := tpgresource.ReplaceVars(d, config, "projects/{{project}}/locations/{{location}}/instances/{{instance}}/dataAccessLabels/{{data_access_label_id}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + log.Printf("[DEBUG] Finished creating DataAccessLabel %q: %#v", d.Id(), res) + + return resourceChronicleDataAccessLabelRead(d, meta) +} + +func resourceChronicleDataAccessLabelRead(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, "{{ChronicleBasePath}}projects/{{project}}/locations/{{location}}/instances/{{instance}}/dataAccessLabels/{{data_access_label_id}}") + if err != nil { + return err + } + + billingProject := "" + + project, err := tpgresource.GetProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for DataAccessLabel: %s", err) + } + billingProject = project + + // 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("ChronicleDataAccessLabel %q", d.Id())) + } + + if err := d.Set("project", project); err != nil { + return fmt.Errorf("Error reading DataAccessLabel: %s", err) + } + + if err := d.Set("author", flattenChronicleDataAccessLabelAuthor(res["author"], d, config)); err != nil { + return fmt.Errorf("Error reading DataAccessLabel: %s", err) + } + if err := d.Set("last_editor", flattenChronicleDataAccessLabelLastEditor(res["lastEditor"], d, config)); err != nil { + return fmt.Errorf("Error reading DataAccessLabel: %s", err) + } + if err := d.Set("description", flattenChronicleDataAccessLabelDescription(res["description"], d, config)); err != nil { + return fmt.Errorf("Error reading DataAccessLabel: %s", err) + } + if err := d.Set("udm_query", flattenChronicleDataAccessLabelUdmQuery(res["udmQuery"], d, config)); err != nil { + return fmt.Errorf("Error reading DataAccessLabel: %s", err) + } + if err := d.Set("name", flattenChronicleDataAccessLabelName(res["name"], d, config)); err != nil { + return fmt.Errorf("Error reading DataAccessLabel: %s", err) + } + if err := d.Set("display_name", flattenChronicleDataAccessLabelDisplayName(res["displayName"], d, config)); err != nil { + return fmt.Errorf("Error reading DataAccessLabel: %s", err) + } + if err := d.Set("create_time", flattenChronicleDataAccessLabelCreateTime(res["createTime"], d, config)); err != nil { + return fmt.Errorf("Error reading DataAccessLabel: %s", err) + } + if err := d.Set("update_time", flattenChronicleDataAccessLabelUpdateTime(res["updateTime"], d, config)); err != nil { + return fmt.Errorf("Error reading DataAccessLabel: %s", err) + } + + return nil +} + +func resourceChronicleDataAccessLabelUpdate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*transport_tpg.Config) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + if err != nil { + return err + } + + billingProject := "" + + project, err := tpgresource.GetProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for DataAccessLabel: %s", err) + } + billingProject = project + + obj := make(map[string]interface{}) + descriptionProp, err := expandChronicleDataAccessLabelDescription(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 + } + udmQueryProp, err := expandChronicleDataAccessLabelUdmQuery(d.Get("udm_query"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("udm_query"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, udmQueryProp)) { + obj["udmQuery"] = udmQueryProp + } + + url, err := tpgresource.ReplaceVars(d, config, "{{ChronicleBasePath}}projects/{{project}}/locations/{{location}}/instances/{{instance}}/dataAccessLabels/{{data_access_label_id}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Updating DataAccessLabel %q: %#v", d.Id(), obj) + headers := make(http.Header) + updateMask := []string{} + + if d.HasChange("description") { + updateMask = append(updateMask, "description") + } + + if d.HasChange("udm_query") { + updateMask = append(updateMask, "udmQuery") + } + // 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 DataAccessLabel %q: %s", d.Id(), err) + } else { + log.Printf("[DEBUG] Finished updating DataAccessLabel %q: %#v", d.Id(), res) + } + + } + + return resourceChronicleDataAccessLabelRead(d, meta) +} + +func resourceChronicleDataAccessLabelDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*transport_tpg.Config) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + if err != nil { + return err + } + + billingProject := "" + + project, err := tpgresource.GetProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for DataAccessLabel: %s", err) + } + billingProject = project + + url, err := tpgresource.ReplaceVars(d, config, "{{ChronicleBasePath}}projects/{{project}}/locations/{{location}}/instances/{{instance}}/dataAccessLabels/{{data_access_label_id}}") + 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 DataAccessLabel %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, "DataAccessLabel") + } + + log.Printf("[DEBUG] Finished deleting DataAccessLabel %q: %#v", d.Id(), res) + return nil +} + +func resourceChronicleDataAccessLabelImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + config := meta.(*transport_tpg.Config) + if err := tpgresource.ParseImportId([]string{ + "^projects/(?P[^/]+)/locations/(?P[^/]+)/instances/(?P[^/]+)/dataAccessLabels/(?P[^/]+)$", + "^(?P[^/]+)/(?P[^/]+)/(?P[^/]+)/(?P[^/]+)$", + "^(?P[^/]+)/(?P[^/]+)/(?P[^/]+)$", + }, d, config); err != nil { + return nil, err + } + + // Replace import id for the resource id + id, err := tpgresource.ReplaceVars(d, config, "projects/{{project}}/locations/{{location}}/instances/{{instance}}/dataAccessLabels/{{data_access_label_id}}") + if err != nil { + return nil, fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + return []*schema.ResourceData{d}, nil +} + +func flattenChronicleDataAccessLabelAuthor(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenChronicleDataAccessLabelLastEditor(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenChronicleDataAccessLabelDescription(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenChronicleDataAccessLabelUdmQuery(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenChronicleDataAccessLabelName(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenChronicleDataAccessLabelDisplayName(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenChronicleDataAccessLabelCreateTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenChronicleDataAccessLabelUpdateTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func expandChronicleDataAccessLabelDescription(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandChronicleDataAccessLabelUdmQuery(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} diff --git a/google-beta/services/chronicle/resource_chronicle_data_access_label_generated_meta.yaml b/google-beta/services/chronicle/resource_chronicle_data_access_label_generated_meta.yaml new file mode 100644 index 0000000000..ad6abc1157 --- /dev/null +++ b/google-beta/services/chronicle/resource_chronicle_data_access_label_generated_meta.yaml @@ -0,0 +1,5 @@ +resource: 'google_chronicle_data_access_label' +generation_type: 'mmv1' +api_service_name: 'chronicle.googleapis.com' +api_version: 'v1beta' +api_resource_type_kind: 'DataAccessLabel' diff --git a/google-beta/services/chronicle/resource_chronicle_data_access_label_generated_test.go b/google-beta/services/chronicle/resource_chronicle_data_access_label_generated_test.go new file mode 100644 index 0000000000..5c7ece0609 --- /dev/null +++ b/google-beta/services/chronicle/resource_chronicle_data_access_label_generated_test.go @@ -0,0 +1,110 @@ +// 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 chronicle_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 TestAccChronicleDataAccessLabel_chronicleDataaccesslabelBasicExample(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "chronicle_id": envvar.GetTestChronicleInstanceIdFromEnv(t), + "random_suffix": acctest.RandString(t, 10), + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderBetaFactories(t), + CheckDestroy: testAccCheckChronicleDataAccessLabelDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccChronicleDataAccessLabel_chronicleDataaccesslabelBasicExample(context), + }, + { + ResourceName: "google_chronicle_data_access_label.example", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"data_access_label_id", "instance", "location"}, + }, + }, + }) +} + +func testAccChronicleDataAccessLabel_chronicleDataaccesslabelBasicExample(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_chronicle_data_access_label" "example" { + provider = "google-beta" + location = "us" + instance = "%{chronicle_id}" + data_access_label_id = "tf-test-label-id%{random_suffix}" + udm_query = "principal.hostname=\"google.com\"" + description = "tf-test-label-description%{random_suffix}" +} +`, context) +} + +func testAccCheckChronicleDataAccessLabelDestroyProducer(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_chronicle_data_access_label" { + continue + } + if strings.HasPrefix(name, "data.") { + continue + } + + config := acctest.GoogleProviderConfig(t) + + url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{ChronicleBasePath}}projects/{{project}}/locations/{{location}}/instances/{{instance}}/dataAccessLabels/{{data_access_label_id}}") + 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("ChronicleDataAccessLabel still exists at %s", url) + } + } + + return nil + } +} diff --git a/google-beta/services/chronicle/resource_chronicle_data_access_label_sweeper.go b/google-beta/services/chronicle/resource_chronicle_data_access_label_sweeper.go new file mode 100644 index 0000000000..7c009f2ba0 --- /dev/null +++ b/google-beta/services/chronicle/resource_chronicle_data_access_label_sweeper.go @@ -0,0 +1,143 @@ +// 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 chronicle + +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("ChronicleDataAccessLabel", testSweepChronicleDataAccessLabel) +} + +// At the time of writing, the CI only passes us-central1 as the region +func testSweepChronicleDataAccessLabel(region string) error { + resourceName := "ChronicleDataAccessLabel" + 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://{{location}}-chronicle.googleapis.com/v1beta/projects/{{project}}/locations/{{location}}/instances/{{instance}}/dataAccessLabels", "?")[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["dataAccessLabels"] + 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{}) + var name string + // Id detected in the delete URL, attempt to use id. + if obj["id"] != nil { + name = tpgresource.GetResourceNameFromSelfLink(obj["id"].(string)) + } else if obj["name"] != nil { + name = tpgresource.GetResourceNameFromSelfLink(obj["name"].(string)) + } else { + log.Printf("[INFO][SWEEPER_LOG] %s resource name and id were nil", resourceName) + return nil + } + // Skip resources that shouldn't be sweeped + if !sweeper.IsSweepableTestResource(name) { + nonPrefixCount++ + continue + } + + deleteTemplate := "https://{{location}}-chronicle.googleapis.com/v1beta/projects/{{project}}/locations/{{location}}/instances/{{instance}}/dataAccessLabels/{{data_access_label_id}}" + 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/google-beta/services/chronicle/resource_chronicle_data_access_label_test.go b/google-beta/services/chronicle/resource_chronicle_data_access_label_test.go new file mode 100644 index 0000000000..0753515cd3 --- /dev/null +++ b/google-beta/services/chronicle/resource_chronicle_data_access_label_test.go @@ -0,0 +1,74 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 +package chronicle_test + +import ( + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + + "github.com/hashicorp/terraform-provider-google-beta/google-beta/acctest" + "github.com/hashicorp/terraform-provider-google-beta/google-beta/envvar" +) + +func TestAccChronicleDataAccessLabel_chronicleDataaccesslabelBasicExample_update(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "chronicle_id": envvar.GetTestChronicleInstanceIdFromEnv(t), + "random_suffix": acctest.RandString(t, 10), + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderBetaFactories(t), + CheckDestroy: testAccCheckChronicleDataAccessLabelDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccChronicleDataAccessLabel_chronicleDataaccesslabelBasicExample_full(context), + }, + { + ResourceName: "google_chronicle_data_access_label.example", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"data_access_label_id", "instance", "location"}, + }, + + { + Config: testAccChronicleDataAccessLabel_chronicleDataaccesslabelBasicExample_update(context), + }, + { + ResourceName: "google_chronicle_data_access_label.example", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"data_access_label_id", "instance", "location"}, + }, + }, + }) +} + +func testAccChronicleDataAccessLabel_chronicleDataaccesslabelBasicExample_full(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_chronicle_data_access_label" "example" { + provider = "google-beta" + location = "us" + instance = "%{chronicle_id}" + data_access_label_id = "tf-test-label-id%{random_suffix}" + udm_query = "principal.hostname=\"google.com\"" + description = "tf-test-label-description%{random_suffix}" +} +`, context) +} + +func testAccChronicleDataAccessLabel_chronicleDataaccesslabelBasicExample_update(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_chronicle_data_access_label" "example" { + provider = "google-beta" + location = "us" + instance = "%{chronicle_id}" + data_access_label_id = "tf-test-label-id%{random_suffix}" + udm_query = "principal.hostname=\"google-updated.com\"" + description = "tf-test-label-updated-description%{random_suffix}" +} +`, context) +} diff --git a/website/docs/r/chronicle_data_access_label.html.markdown b/website/docs/r/chronicle_data_access_label.html.markdown new file mode 100644 index 0000000000..bdeaaed3a3 --- /dev/null +++ b/website/docs/r/chronicle_data_access_label.html.markdown @@ -0,0 +1,148 @@ +--- +# ---------------------------------------------------------------------------- +# +# *** 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: "Chronicle" +description: |- + A DataAccessLabel is a label on events to define user access to data. +--- + +# google_chronicle_data_access_label + +A DataAccessLabel is a label on events to define user access to data. + +~> **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 DataAccessLabel, see: + +* [API documentation](https://cloud.google.com/chronicle/docs/reference/rest/v1alpha/projects.locations.instances.dataAccessLabels) +* How-to Guides + * [Introduction to data RBAC](https://cloud.google.com/chronicle/docs/onboard/onboard-datarbac) + +## Example Usage - Chronicle Dataaccesslabel Basic + + +```hcl +resource "google_chronicle_data_access_label" "example" { + provider = "google-beta" + location = "us" + instance = "00000000-0000-0000-0000-000000000000" + data_access_label_id = "label-id" + udm_query = "principal.hostname=\"google.com\"" + description = "label-description" +} +``` + +## Argument Reference + +The following arguments are supported: + + +* `udm_query` - + (Required) + A UDM query over event data. + +* `location` - + (Required) + The location of the resource. This is the geographical region where the Chronicle instance resides, such as "us" or "europe-west2". + +* `instance` - + (Required) + The unique identifier for the Chronicle instance, which is the same as the customer ID. + +* `data_access_label_id` - + (Required) + Required. The ID to use for the data access label, which will become the label's + display name and the final component of the label's resource name. It must + only contain ASCII lowercase letters, numbers, and dashes; it must begin + with a letter, and it must not exceed 1000 characters. + + +- - - + + +* `description` - + (Optional) + Optional. A description of the data access label for a human reader. + +* `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/{{location}}/instances/{{instance}}/dataAccessLabels/{{data_access_label_id}}` + +* `author` - + Output only. The user who created the data access label. + +* `last_editor` - + Output only. The user who last updated the data access label. + +* `name` - + The unique resource name of the data access label. This unique identifier is generated using values provided for the URL parameters. + Format: + projects/{project}/locations/{location}/instances/{instance}/dataAccessLabels/{data_access_label_id} + +* `display_name` - + Output only. The short name displayed for the label as it appears on event data. This is same as data access label id. + +* `create_time` - + Output only. The time at which the data access label was created. + +* `update_time` - + Output only. The time at which the data access label was last updated. + + +## 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 + + +DataAccessLabel can be imported using any of these accepted formats: + +* `projects/{{project}}/locations/{{location}}/instances/{{instance}}/dataAccessLabels/{{data_access_label_id}}` +* `{{project}}/{{location}}/{{instance}}/{{data_access_label_id}}` +* `{{location}}/{{instance}}/{{data_access_label_id}}` + + +In Terraform v1.5.0 and later, use an [`import` block](https://developer.hashicorp.com/terraform/language/import) to import DataAccessLabel using one of the formats above. For example: + +```tf +import { + id = "projects/{{project}}/locations/{{location}}/instances/{{instance}}/dataAccessLabels/{{data_access_label_id}}" + to = google_chronicle_data_access_label.default +} +``` + +When using the [`terraform import` command](https://developer.hashicorp.com/terraform/cli/commands/import), DataAccessLabel can be imported using one of the formats above. For example: + +``` +$ terraform import google_chronicle_data_access_label.default projects/{{project}}/locations/{{location}}/instances/{{instance}}/dataAccessLabels/{{data_access_label_id}} +$ terraform import google_chronicle_data_access_label.default {{project}}/{{location}}/{{instance}}/{{data_access_label_id}} +$ terraform import google_chronicle_data_access_label.default {{location}}/{{instance}}/{{data_access_label_id}} +``` + +## User Project Overrides + +This resource supports [User Project Overrides](https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/provider_reference#user_project_override).