diff --git a/.changelog/11004.txt b/.changelog/11004.txt new file mode 100644 index 00000000000..64f301abd15 --- /dev/null +++ b/.changelog/11004.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +`google_scc_project_notification_config` +``` \ No newline at end of file diff --git a/google/provider/provider_mmv1_resources.go b/google/provider/provider_mmv1_resources.go index de8fc9d96db..3f77fb8346d 100644 --- a/google/provider/provider_mmv1_resources.go +++ b/google/provider/provider_mmv1_resources.go @@ -420,9 +420,9 @@ var handwrittenIAMDatasources = map[string]*schema.Resource{ } // Resources -// Generated resources: 432 +// Generated resources: 433 // Generated IAM resources: 252 -// Total generated resources: 684 +// Total generated resources: 685 var generatedResources = map[string]*schema.Resource{ "google_folder_access_approval_settings": accessapproval.ResourceAccessApprovalFolderSettings(), "google_organization_access_approval_settings": accessapproval.ResourceAccessApprovalOrganizationSettings(), @@ -1013,6 +1013,7 @@ var generatedResources = map[string]*schema.Resource{ "google_scc_notification_config": securitycenter.ResourceSecurityCenterNotificationConfig(), "google_scc_organization_custom_module": securitycenter.ResourceSecurityCenterOrganizationCustomModule(), "google_scc_project_custom_module": securitycenter.ResourceSecurityCenterProjectCustomModule(), + "google_scc_project_notification_config": securitycenter.ResourceSecurityCenterProjectNotificationConfig(), "google_scc_source": securitycenter.ResourceSecurityCenterSource(), "google_scc_source_iam_binding": tpgiamresource.ResourceIamBinding(securitycenter.SecurityCenterSourceIamSchema, securitycenter.SecurityCenterSourceIamUpdaterProducer, securitycenter.SecurityCenterSourceIdParseFunc), "google_scc_source_iam_member": tpgiamresource.ResourceIamMember(securitycenter.SecurityCenterSourceIamSchema, securitycenter.SecurityCenterSourceIamUpdaterProducer, securitycenter.SecurityCenterSourceIdParseFunc), diff --git a/google/services/securitycenter/resource_scc_project_notification_config.go b/google/services/securitycenter/resource_scc_project_notification_config.go new file mode 100644 index 00000000000..3e063c201e7 --- /dev/null +++ b/google/services/securitycenter/resource_scc_project_notification_config.go @@ -0,0 +1,517 @@ +// 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 securitycenter + +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-plugin-sdk/v2/helper/validation" + + "github.com/hashicorp/terraform-provider-google/google/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" +) + +func ResourceSecurityCenterProjectNotificationConfig() *schema.Resource { + return &schema.Resource{ + Create: resourceSecurityCenterProjectNotificationConfigCreate, + Read: resourceSecurityCenterProjectNotificationConfigRead, + Update: resourceSecurityCenterProjectNotificationConfigUpdate, + Delete: resourceSecurityCenterProjectNotificationConfigDelete, + + Importer: &schema.ResourceImporter{ + State: resourceSecurityCenterProjectNotificationConfigImport, + }, + + 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{ + "config_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `This must be unique within the organization.`, + }, + "pubsub_topic": { + Type: schema.TypeString, + Required: true, + Description: `The Pub/Sub topic to send notifications to. Its format is +"projects/[project_id]/topics/[topic]".`, + }, + "streaming_config": { + Type: schema.TypeList, + Required: true, + Description: `The config for triggering streaming-based notifications.`, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "filter": { + Type: schema.TypeString, + Required: true, + Description: `Expression that defines the filter to apply across create/update +events of assets or findings as specified by the event type. The +expression is a list of zero or more restrictions combined via +logical operators AND and OR. Parentheses are supported, and OR +has higher precedence than AND. + +Restrictions have the form and may have +a - character in front of them to indicate negation. The fields +map to those defined in the corresponding resource. + +The supported operators are: + +* = for all value types. +* >, <, >=, <= for integer values. +* :, meaning substring matching, for strings. + +The supported value types are: + +* string literals in quotes. +* integer literals without quotes. +* boolean literals true and false without quotes. + +See +[Filtering notifications](https://cloud.google.com/security-command-center/docs/how-to-api-filter-notifications) +for information on how to write a filter.`, + }, + }, + }, + }, + "description": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringLenBetween(0, 1024), + Description: `The description of the notification config (max of 1024 characters).`, + }, + "name": { + Type: schema.TypeString, + Computed: true, + Description: `The resource name of this notification config, in the format +'projects/{{projectId}}/notificationConfigs/{{config_id}}'.`, + }, + "service_account": { + Type: schema.TypeString, + Computed: true, + Description: `The service account that needs "pubsub.topics.publish" permission to +publish to the Pub/Sub topic.`, + }, + "project": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, + }, + UseJSONNumber: true, + } +} + +func resourceSecurityCenterProjectNotificationConfigCreate(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 := expandSecurityCenterProjectNotificationConfigDescription(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 + } + pubsubTopicProp, err := expandSecurityCenterProjectNotificationConfigPubsubTopic(d.Get("pubsub_topic"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("pubsub_topic"); !tpgresource.IsEmptyValue(reflect.ValueOf(pubsubTopicProp)) && (ok || !reflect.DeepEqual(v, pubsubTopicProp)) { + obj["pubsubTopic"] = pubsubTopicProp + } + streamingConfigProp, err := expandSecurityCenterProjectNotificationConfigStreamingConfig(d.Get("streaming_config"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("streaming_config"); !tpgresource.IsEmptyValue(reflect.ValueOf(streamingConfigProp)) && (ok || !reflect.DeepEqual(v, streamingConfigProp)) { + obj["streamingConfig"] = streamingConfigProp + } + + url, err := tpgresource.ReplaceVars(d, config, "{{SecurityCenterBasePath}}projects/{{project}}/notificationConfigs?configId={{config_id}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Creating new ProjectNotificationConfig: %#v", obj) + billingProject := "" + + project, err := tpgresource.GetProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for ProjectNotificationConfig: %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 ProjectNotificationConfig: %s", err) + } + if err := d.Set("name", flattenSecurityCenterProjectNotificationConfigName(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, "{{name}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + // `name` is autogenerated from the api so needs to be set post-create + name, ok := res["name"] + if !ok { + respBody, ok := res["response"] + if !ok { + return fmt.Errorf("Create response didn't contain critical fields. Create may not have succeeded.") + } + + name, ok = respBody.(map[string]interface{})["name"] + if !ok { + return fmt.Errorf("Create response didn't contain critical fields. Create may not have succeeded.") + } + } + if err := d.Set("name", name.(string)); err != nil { + return fmt.Errorf("Error setting name: %s", err) + } + d.SetId(name.(string)) + + log.Printf("[DEBUG] Finished creating ProjectNotificationConfig %q: %#v", d.Id(), res) + + return resourceSecurityCenterProjectNotificationConfigRead(d, meta) +} + +func resourceSecurityCenterProjectNotificationConfigRead(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, "{{SecurityCenterBasePath}}{{name}}") + if err != nil { + return err + } + + billingProject := "" + + project, err := tpgresource.GetProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for ProjectNotificationConfig: %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("SecurityCenterProjectNotificationConfig %q", d.Id())) + } + + if err := d.Set("project", project); err != nil { + return fmt.Errorf("Error reading ProjectNotificationConfig: %s", err) + } + + if err := d.Set("name", flattenSecurityCenterProjectNotificationConfigName(res["name"], d, config)); err != nil { + return fmt.Errorf("Error reading ProjectNotificationConfig: %s", err) + } + if err := d.Set("description", flattenSecurityCenterProjectNotificationConfigDescription(res["description"], d, config)); err != nil { + return fmt.Errorf("Error reading ProjectNotificationConfig: %s", err) + } + if err := d.Set("pubsub_topic", flattenSecurityCenterProjectNotificationConfigPubsubTopic(res["pubsubTopic"], d, config)); err != nil { + return fmt.Errorf("Error reading ProjectNotificationConfig: %s", err) + } + if err := d.Set("service_account", flattenSecurityCenterProjectNotificationConfigServiceAccount(res["serviceAccount"], d, config)); err != nil { + return fmt.Errorf("Error reading ProjectNotificationConfig: %s", err) + } + if err := d.Set("streaming_config", flattenSecurityCenterProjectNotificationConfigStreamingConfig(res["streamingConfig"], d, config)); err != nil { + return fmt.Errorf("Error reading ProjectNotificationConfig: %s", err) + } + + return nil +} + +func resourceSecurityCenterProjectNotificationConfigUpdate(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 ProjectNotificationConfig: %s", err) + } + billingProject = project + + obj := make(map[string]interface{}) + descriptionProp, err := expandSecurityCenterProjectNotificationConfigDescription(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 + } + pubsubTopicProp, err := expandSecurityCenterProjectNotificationConfigPubsubTopic(d.Get("pubsub_topic"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("pubsub_topic"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, pubsubTopicProp)) { + obj["pubsubTopic"] = pubsubTopicProp + } + streamingConfigProp, err := expandSecurityCenterProjectNotificationConfigStreamingConfig(d.Get("streaming_config"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("streaming_config"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, streamingConfigProp)) { + obj["streamingConfig"] = streamingConfigProp + } + + url, err := tpgresource.ReplaceVars(d, config, "{{SecurityCenterBasePath}}{{name}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Updating ProjectNotificationConfig %q: %#v", d.Id(), obj) + headers := make(http.Header) + updateMask := []string{} + + if d.HasChange("description") { + updateMask = append(updateMask, "description") + } + + if d.HasChange("pubsub_topic") { + updateMask = append(updateMask, "pubsubTopic") + } + + if d.HasChange("streaming_config") { + updateMask = append(updateMask, "streamingConfig.filter") + } + // 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 ProjectNotificationConfig %q: %s", d.Id(), err) + } else { + log.Printf("[DEBUG] Finished updating ProjectNotificationConfig %q: %#v", d.Id(), res) + } + + } + + return resourceSecurityCenterProjectNotificationConfigRead(d, meta) +} + +func resourceSecurityCenterProjectNotificationConfigDelete(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 ProjectNotificationConfig: %s", err) + } + billingProject = project + + url, err := tpgresource.ReplaceVars(d, config, "{{SecurityCenterBasePath}}{{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 ProjectNotificationConfig %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, "ProjectNotificationConfig") + } + + log.Printf("[DEBUG] Finished deleting ProjectNotificationConfig %q: %#v", d.Id(), res) + return nil +} + +func resourceSecurityCenterProjectNotificationConfigImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + + config := meta.(*transport_tpg.Config) + + // current import_formats can't import fields with forward slashes in their value + if err := tpgresource.ParseImportId([]string{"(?P.+)"}, d, config); err != nil { + return nil, err + } + + stringParts := strings.Split(d.Get("name").(string), "/") + if len(stringParts) < 2 { + return nil, fmt.Errorf( + "Could not split project from name: %s", + d.Get("name"), + ) + } + + if err := d.Set("project", stringParts[1]); err != nil { + return nil, fmt.Errorf("Error setting project: %s", err) + } + return []*schema.ResourceData{d}, nil +} + +func flattenSecurityCenterProjectNotificationConfigName(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenSecurityCenterProjectNotificationConfigDescription(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenSecurityCenterProjectNotificationConfigPubsubTopic(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenSecurityCenterProjectNotificationConfigServiceAccount(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenSecurityCenterProjectNotificationConfigStreamingConfig(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + if v == nil { + return nil + } + original := v.(map[string]interface{}) + if len(original) == 0 { + return nil + } + transformed := make(map[string]interface{}) + transformed["filter"] = + flattenSecurityCenterProjectNotificationConfigStreamingConfigFilter(original["filter"], d, config) + return []interface{}{transformed} +} +func flattenSecurityCenterProjectNotificationConfigStreamingConfigFilter(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func expandSecurityCenterProjectNotificationConfigDescription(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandSecurityCenterProjectNotificationConfigPubsubTopic(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandSecurityCenterProjectNotificationConfigStreamingConfig(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + l := v.([]interface{}) + if len(l) == 0 || l[0] == nil { + return nil, nil + } + raw := l[0] + original := raw.(map[string]interface{}) + transformed := make(map[string]interface{}) + + transformedFilter, err := expandSecurityCenterProjectNotificationConfigStreamingConfigFilter(original["filter"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedFilter); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["filter"] = transformedFilter + } + + return transformed, nil +} + +func expandSecurityCenterProjectNotificationConfigStreamingConfigFilter(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} diff --git a/google/services/securitycenter/resource_scc_project_notification_config_generated_test.go b/google/services/securitycenter/resource_scc_project_notification_config_generated_test.go new file mode 100644 index 00000000000..5b0ce694911 --- /dev/null +++ b/google/services/securitycenter/resource_scc_project_notification_config_generated_test.go @@ -0,0 +1,116 @@ +// 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 securitycenter_test + +import ( + "fmt" + "strings" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + + "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" +) + +func TestAccSecurityCenterProjectNotificationConfig_sccProjectNotificationConfigBasicExample(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: testAccCheckSecurityCenterProjectNotificationConfigDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccSecurityCenterProjectNotificationConfig_sccProjectNotificationConfigBasicExample(context), + }, + { + ResourceName: "google_scc_project_notification_config.custom_notification_config", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"config_id", "project"}, + }, + }, + }) +} + +func testAccSecurityCenterProjectNotificationConfig_sccProjectNotificationConfigBasicExample(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_pubsub_topic" "scc_project_notification" { + name = "tf-test-my-topic%{random_suffix}" +} + +resource "google_scc_project_notification_config" "custom_notification_config" { + config_id = "tf-test-my-config%{random_suffix}" + project = "%{project}" + description = "My custom Cloud Security Command Center Finding Notification Configuration" + pubsub_topic = google_pubsub_topic.scc_project_notification.id + + streaming_config { + filter = "category = \"OPEN_FIREWALL\" AND state = \"ACTIVE\"" + } +} +`, context) +} + +func testAccCheckSecurityCenterProjectNotificationConfigDestroyProducer(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_scc_project_notification_config" { + continue + } + if strings.HasPrefix(name, "data.") { + continue + } + + config := acctest.GoogleProviderConfig(t) + + url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{SecurityCenterBasePath}}{{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("SecurityCenterProjectNotificationConfig still exists at %s", url) + } + } + + return nil + } +} diff --git a/google/services/securitycenter/resource_scc_project_notification_config_sweeper.go b/google/services/securitycenter/resource_scc_project_notification_config_sweeper.go new file mode 100644 index 00000000000..a358836c690 --- /dev/null +++ b/google/services/securitycenter/resource_scc_project_notification_config_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 securitycenter + +import ( + "context" + "log" + "strings" + "testing" + + "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/sweeper" + "github.com/hashicorp/terraform-provider-google/google/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" +) + +func init() { + sweeper.AddTestSweepers("SecurityCenterProjectNotificationConfig", testSweepSecurityCenterProjectNotificationConfig) +} + +// At the time of writing, the CI only passes us-central1 as the region +func testSweepSecurityCenterProjectNotificationConfig(region string) error { + resourceName := "SecurityCenterProjectNotificationConfig" + 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://securitycenter.googleapis.com/v1/projects/{{project}}/notificationConfigs", "?")[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["projectNotificationConfigs"] + 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://securitycenter.googleapis.com/v1/{{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/google/services/securitycenter/resource_scc_project_notification_config_test.go b/google/services/securitycenter/resource_scc_project_notification_config_test.go new file mode 100644 index 00000000000..9f0c437229f --- /dev/null +++ b/google/services/securitycenter/resource_scc_project_notification_config_test.go @@ -0,0 +1,65 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 +package securitycenter_test + +import ( + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/envvar" +) + +func TestAccSecurityCenterProjectNotificationConfig_updateStreamingConfigFilter(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: testAccCheckSecurityCenterProjectNotificationConfigDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccSecurityCenterProjectNotificationConfig_sccProjectNotificationConfigBasicExample(context), + }, + { + ResourceName: "google_scc_project_notification_config.custom_notification_config", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"project", "config_id"}, + }, + { + Config: testAccSecurityCenterProjectNotificationConfig_updateStreamingConfigFilter(context), + }, + { + ResourceName: "google_scc_project_notification_config.custom_notification_config", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"project", "config_id"}, + }, + }, + }) +} + +func testAccSecurityCenterProjectNotificationConfig_updateStreamingConfigFilter(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_pubsub_topic" "scc_project_notification" { + name = "tf-test-my-topic%{random_suffix}" +} + +resource "google_scc_project_notification_config" "custom_notification_config" { + config_id = "tf-test-my-config%{random_suffix}" + project = "%{project}" + description = "My custom Cloud Security Command Center Finding Notification Configuration" + pubsub_topic = google_pubsub_topic.scc_project_notification.id + + streaming_config { + filter = "category = \"OPEN_FIREWALL\"" + } +} +`, context) +} diff --git a/website/docs/r/scc_project_notification_config.html.markdown b/website/docs/r/scc_project_notification_config.html.markdown new file mode 100644 index 00000000000..dcb138d4c3a --- /dev/null +++ b/website/docs/r/scc_project_notification_config.html.markdown @@ -0,0 +1,165 @@ +--- +# ---------------------------------------------------------------------------- +# +# *** 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: "Security Command Center (SCC)" +description: |- + A Cloud Security Command Center (Cloud SCC) notification configs. +--- + +# google_scc_project_notification_config + +A Cloud Security Command Center (Cloud SCC) notification configs. A +notification config is a Cloud SCC resource that contains the +configuration to send notifications for create/update events of +findings, assets and etc. +~> **Note:** In order to use Cloud SCC resources, your organization must be enrolled +in [SCC Standard/Premium](https://cloud.google.com/security-command-center/docs/quickstart-security-command-center). +Without doing so, you may run into errors during resource creation. + + +To get more information about ProjectNotificationConfig, see: + +* [API documentation](https://cloud.google.com/security-command-center/docs/reference/rest/v1/projects.notificationConfigs) +* How-to Guides + * [Official Documentation](https://cloud.google.com/security-command-center/docs) + +## Example Usage - Scc Project Notification Config Basic + + +```hcl +resource "google_pubsub_topic" "scc_project_notification" { + name = "my-topic" +} + +resource "google_scc_project_notification_config" "custom_notification_config" { + config_id = "my-config" + project = "my-project-name" + description = "My custom Cloud Security Command Center Finding Notification Configuration" + pubsub_topic = google_pubsub_topic.scc_project_notification.id + + streaming_config { + filter = "category = \"OPEN_FIREWALL\" AND state = \"ACTIVE\"" + } +} +``` + +## Argument Reference + +The following arguments are supported: + + +* `pubsub_topic` - + (Required) + The Pub/Sub topic to send notifications to. Its format is + "projects/[project_id]/topics/[topic]". + +* `streaming_config` - + (Required) + The config for triggering streaming-based notifications. + Structure is [documented below](#nested_streaming_config). + +* `config_id` - + (Required) + This must be unique within the organization. + + +The `streaming_config` block supports: + +* `filter` - + (Required) + Expression that defines the filter to apply across create/update + events of assets or findings as specified by the event type. The + expression is a list of zero or more restrictions combined via + logical operators AND and OR. Parentheses are supported, and OR + has higher precedence than AND. + Restrictions have the form and may have + a - character in front of them to indicate negation. The fields + map to those defined in the corresponding resource. + The supported operators are: + * = for all value types. + * >, <, >=, <= for integer values. + * :, meaning substring matching, for strings. + The supported value types are: + * string literals in quotes. + * integer literals without quotes. + * boolean literals true and false without quotes. + See + [Filtering notifications](https://cloud.google.com/security-command-center/docs/how-to-api-filter-notifications) + for information on how to write a filter. + +- - - + + +* `description` - + (Optional) + The description of the notification config (max of 1024 characters). + +* `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 `{{name}}` + +* `name` - + The resource name of this notification config, in the format + `projects/{{projectId}}/notificationConfigs/{{config_id}}`. + +* `service_account` - + The service account that needs "pubsub.topics.publish" permission to + publish to the Pub/Sub topic. + + +## 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 + + +ProjectNotificationConfig can be imported using any of these accepted formats: + +* `projects/{{project}}/notificationConfigs/{{name}}` +* `{{project}}/{{name}}` +* `{{name}}` + + +In Terraform v1.5.0 and later, use an [`import` block](https://developer.hashicorp.com/terraform/language/import) to import ProjectNotificationConfig using one of the formats above. For example: + +```tf +import { + id = "projects/{{project}}/notificationConfigs/{{name}}" + to = google_scc_project_notification_config.default +} +``` + +When using the [`terraform import` command](https://developer.hashicorp.com/terraform/cli/commands/import), ProjectNotificationConfig can be imported using one of the formats above. For example: + +``` +$ terraform import google_scc_project_notification_config.default projects/{{project}}/notificationConfigs/{{name}} +$ terraform import google_scc_project_notification_config.default {{project}}/{{name}} +$ terraform import google_scc_project_notification_config.default {{name}} +``` + +## User Project Overrides + +This resource supports [User Project Overrides](https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/provider_reference#user_project_override).