diff --git a/.changelog/12579.txt b/.changelog/12579.txt new file mode 100644 index 00000000000..2bb590aca79 --- /dev/null +++ b/.changelog/12579.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +networkmanagement: promoted `google_network_management_vpc_flow_logs_config` from Beta to GA +``` \ No newline at end of file diff --git a/google/provider/provider_mmv1_resources.go b/google/provider/provider_mmv1_resources.go index 4527ea0b85c..25166486baf 100644 --- a/google/provider/provider_mmv1_resources.go +++ b/google/provider/provider_mmv1_resources.go @@ -462,9 +462,9 @@ var handwrittenIAMDatasources = map[string]*schema.Resource{ } // Resources -// Generated resources: 498 +// Generated resources: 499 // Generated IAM resources: 261 -// Total generated resources: 759 +// Total generated resources: 760 var generatedResources = map[string]*schema.Resource{ "google_folder_access_approval_settings": accessapproval.ResourceAccessApprovalFolderSettings(), "google_organization_access_approval_settings": accessapproval.ResourceAccessApprovalOrganizationSettings(), @@ -1018,6 +1018,7 @@ var generatedResources = map[string]*schema.Resource{ "google_network_connectivity_service_connection_policy": networkconnectivity.ResourceNetworkConnectivityServiceConnectionPolicy(), "google_network_connectivity_spoke": networkconnectivity.ResourceNetworkConnectivitySpoke(), "google_network_management_connectivity_test": networkmanagement.ResourceNetworkManagementConnectivityTest(), + "google_network_management_vpc_flow_logs_config": networkmanagement.ResourceNetworkManagementVpcFlowLogsConfig(), "google_network_security_address_group": networksecurity.ResourceNetworkSecurityAddressGroup(), "google_network_security_authz_policy": networksecurity.ResourceNetworkSecurityAuthzPolicy(), "google_network_security_client_tls_policy": networksecurity.ResourceNetworkSecurityClientTlsPolicy(), diff --git a/google/services/networkmanagement/resource_network_management_vpc_flow_logs_config.go b/google/services/networkmanagement/resource_network_management_vpc_flow_logs_config.go new file mode 100644 index 00000000000..9c4708fc16f --- /dev/null +++ b/google/services/networkmanagement/resource_network_management_vpc_flow_logs_config.go @@ -0,0 +1,783 @@ +// 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 networkmanagement + +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/google/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" +) + +func ResourceNetworkManagementVpcFlowLogsConfig() *schema.Resource { + return &schema.Resource{ + Create: resourceNetworkManagementVpcFlowLogsConfigCreate, + Read: resourceNetworkManagementVpcFlowLogsConfigRead, + Update: resourceNetworkManagementVpcFlowLogsConfigUpdate, + Delete: resourceNetworkManagementVpcFlowLogsConfigDelete, + + Importer: &schema.ResourceImporter{ + State: resourceNetworkManagementVpcFlowLogsConfigImport, + }, + + 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.SetLabelsDiff, + tpgresource.DefaultProviderProject, + ), + + Schema: map[string]*schema.Schema{ + "location": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `Resource ID segment making up resource 'name'. It identifies the resource +within its parent collection as described in https://google.aip.dev/122. See documentation +for resource type 'networkmanagement.googleapis.com/VpcFlowLogsConfig'.`, + }, + "vpc_flow_logs_config_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `Required. ID of the 'VpcFlowLogsConfig'.`, + }, + "aggregation_interval": { + Type: schema.TypeString, + Computed: true, + Optional: true, + Description: `Optional. The aggregation interval for the logs. Default value is +INTERVAL_5_SEC. Possible values: AGGREGATION_INTERVAL_UNSPECIFIED INTERVAL_5_SEC INTERVAL_30_SEC INTERVAL_1_MIN INTERVAL_5_MIN INTERVAL_10_MIN INTERVAL_15_MIN"`, + }, + "description": { + Type: schema.TypeString, + Optional: true, + Description: `Optional. The user-supplied description of the VPC Flow Logs configuration. Maximum +of 512 characters.`, + }, + "filter_expr": { + Type: schema.TypeString, + Optional: true, + Description: `Optional. Export filter used to define which VPC Flow Logs should be logged.`, + }, + "flow_sampling": { + Type: schema.TypeFloat, + Computed: true, + Optional: true, + Description: `Optional. The value of the field must be in (0, 1]. The sampling rate +of VPC Flow Logs where 1.0 means all collected logs are reported. Setting the +sampling rate to 0.0 is not allowed. If you want to disable VPC Flow Logs, use +the state field instead. Default value is 1.0.`, + }, + "interconnect_attachment": { + Type: schema.TypeString, + Optional: true, + Description: `Traffic will be logged from the Interconnect Attachment. Format: projects/{project_id}/regions/{region}/interconnectAttachments/{name}`, + }, + "labels": { + Type: schema.TypeMap, + Optional: true, + Description: `Optional. Resource labels to represent user-provided metadata. + + +**Note**: This field is non-authoritative, and will only manage the labels present in your configuration. +Please refer to the field 'effective_labels' for all of the labels present on the resource.`, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "metadata": { + Type: schema.TypeString, + Computed: true, + Optional: true, + Description: `Optional. Configures whether all, none or a subset of metadata fields +should be added to the reported VPC flow logs. Default value is INCLUDE_ALL_METADATA. + Possible values: METADATA_UNSPECIFIED INCLUDE_ALL_METADATA EXCLUDE_ALL_METADATA CUSTOM_METADATA`, + }, + "metadata_fields": { + Type: schema.TypeList, + Optional: true, + Description: `Optional. Custom metadata fields to include in the reported VPC flow +logs. Can only be specified if \"metadata\" was set to CUSTOM_METADATA.`, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "state": { + Type: schema.TypeString, + Computed: true, + Optional: true, + Description: `Optional. The state of the VPC Flow Log configuration. Default value +is ENABLED. When creating a new configuration, it must be enabled. Possible`, + }, + "vpn_tunnel": { + Type: schema.TypeString, + Optional: true, + Description: `Traffic will be logged from the VPN Tunnel. Format: projects/{project_id}/regions/{region}/vpnTunnels/{name}`, + }, + "create_time": { + Type: schema.TypeString, + Computed: true, + Description: `Output only. The time the config was created.`, + }, + "effective_labels": { + Type: schema.TypeMap, + Computed: true, + Description: `All of labels (key/value pairs) present on the resource in GCP, including the labels configured through Terraform, other clients and services.`, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "name": { + Type: schema.TypeString, + Computed: true, + Description: `Identifier. Unique name of the configuration using the form: 'projects/{project_id}/locations/global/vpcFlowLogsConfigs/{vpc_flow_logs_config_id}'`, + }, + "terraform_labels": { + Type: schema.TypeMap, + Computed: true, + Description: `The combination of labels configured directly on the resource + and default labels configured on the provider.`, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "update_time": { + Type: schema.TypeString, + Computed: true, + Description: `Output only. The time the config was updated.`, + }, + "project": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, + }, + UseJSONNumber: true, + } +} + +func resourceNetworkManagementVpcFlowLogsConfigCreate(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 := expandNetworkManagementVpcFlowLogsConfigDescription(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 + } + stateProp, err := expandNetworkManagementVpcFlowLogsConfigState(d.Get("state"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("state"); !tpgresource.IsEmptyValue(reflect.ValueOf(stateProp)) && (ok || !reflect.DeepEqual(v, stateProp)) { + obj["state"] = stateProp + } + aggregationIntervalProp, err := expandNetworkManagementVpcFlowLogsConfigAggregationInterval(d.Get("aggregation_interval"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("aggregation_interval"); !tpgresource.IsEmptyValue(reflect.ValueOf(aggregationIntervalProp)) && (ok || !reflect.DeepEqual(v, aggregationIntervalProp)) { + obj["aggregationInterval"] = aggregationIntervalProp + } + flowSamplingProp, err := expandNetworkManagementVpcFlowLogsConfigFlowSampling(d.Get("flow_sampling"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("flow_sampling"); !tpgresource.IsEmptyValue(reflect.ValueOf(flowSamplingProp)) && (ok || !reflect.DeepEqual(v, flowSamplingProp)) { + obj["flowSampling"] = flowSamplingProp + } + metadataProp, err := expandNetworkManagementVpcFlowLogsConfigMetadata(d.Get("metadata"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("metadata"); !tpgresource.IsEmptyValue(reflect.ValueOf(metadataProp)) && (ok || !reflect.DeepEqual(v, metadataProp)) { + obj["metadata"] = metadataProp + } + metadataFieldsProp, err := expandNetworkManagementVpcFlowLogsConfigMetadataFields(d.Get("metadata_fields"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("metadata_fields"); !tpgresource.IsEmptyValue(reflect.ValueOf(metadataFieldsProp)) && (ok || !reflect.DeepEqual(v, metadataFieldsProp)) { + obj["metadataFields"] = metadataFieldsProp + } + filterExprProp, err := expandNetworkManagementVpcFlowLogsConfigFilterExpr(d.Get("filter_expr"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("filter_expr"); !tpgresource.IsEmptyValue(reflect.ValueOf(filterExprProp)) && (ok || !reflect.DeepEqual(v, filterExprProp)) { + obj["filterExpr"] = filterExprProp + } + interconnectAttachmentProp, err := expandNetworkManagementVpcFlowLogsConfigInterconnectAttachment(d.Get("interconnect_attachment"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("interconnect_attachment"); !tpgresource.IsEmptyValue(reflect.ValueOf(interconnectAttachmentProp)) && (ok || !reflect.DeepEqual(v, interconnectAttachmentProp)) { + obj["interconnectAttachment"] = interconnectAttachmentProp + } + vpnTunnelProp, err := expandNetworkManagementVpcFlowLogsConfigVpnTunnel(d.Get("vpn_tunnel"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("vpn_tunnel"); !tpgresource.IsEmptyValue(reflect.ValueOf(vpnTunnelProp)) && (ok || !reflect.DeepEqual(v, vpnTunnelProp)) { + obj["vpnTunnel"] = vpnTunnelProp + } + labelsProp, err := expandNetworkManagementVpcFlowLogsConfigEffectiveLabels(d.Get("effective_labels"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("effective_labels"); !tpgresource.IsEmptyValue(reflect.ValueOf(labelsProp)) && (ok || !reflect.DeepEqual(v, labelsProp)) { + obj["labels"] = labelsProp + } + + url, err := tpgresource.ReplaceVars(d, config, "{{NetworkManagementBasePath}}projects/{{project}}/locations/{{location}}/vpcFlowLogsConfigs?vpcFlowLogsConfigId={{vpc_flow_logs_config_id}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Creating new VpcFlowLogsConfig: %#v", obj) + billingProject := "" + + project, err := tpgresource.GetProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for VpcFlowLogsConfig: %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 VpcFlowLogsConfig: %s", err) + } + + // Store the ID now + id, err := tpgresource.ReplaceVars(d, config, "projects/{{project}}/locations/{{location}}/vpcFlowLogsConfigs/{{vpc_flow_logs_config_id}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + // Use the resource in the operation response to populate + // identity fields and d.Id() before read + var opRes map[string]interface{} + err = NetworkManagementOperationWaitTimeWithResponse( + config, res, &opRes, project, "Creating VpcFlowLogsConfig", userAgent, + d.Timeout(schema.TimeoutCreate)) + if err != nil { + // The resource didn't actually create + d.SetId("") + + return fmt.Errorf("Error waiting to create VpcFlowLogsConfig: %s", err) + } + + if err := d.Set("name", flattenNetworkManagementVpcFlowLogsConfigName(opRes["name"], d, config)); err != nil { + return err + } + + // This may have caused the ID to update - update it if so. + id, err = tpgresource.ReplaceVars(d, config, "projects/{{project}}/locations/{{location}}/vpcFlowLogsConfigs/{{vpc_flow_logs_config_id}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + log.Printf("[DEBUG] Finished creating VpcFlowLogsConfig %q: %#v", d.Id(), res) + + return resourceNetworkManagementVpcFlowLogsConfigRead(d, meta) +} + +func resourceNetworkManagementVpcFlowLogsConfigRead(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, "{{NetworkManagementBasePath}}projects/{{project}}/locations/{{location}}/vpcFlowLogsConfigs/{{vpc_flow_logs_config_id}}") + if err != nil { + return err + } + + billingProject := "" + + project, err := tpgresource.GetProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for VpcFlowLogsConfig: %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("NetworkManagementVpcFlowLogsConfig %q", d.Id())) + } + + if err := d.Set("project", project); err != nil { + return fmt.Errorf("Error reading VpcFlowLogsConfig: %s", err) + } + + if err := d.Set("name", flattenNetworkManagementVpcFlowLogsConfigName(res["name"], d, config)); err != nil { + return fmt.Errorf("Error reading VpcFlowLogsConfig: %s", err) + } + if err := d.Set("description", flattenNetworkManagementVpcFlowLogsConfigDescription(res["description"], d, config)); err != nil { + return fmt.Errorf("Error reading VpcFlowLogsConfig: %s", err) + } + if err := d.Set("state", flattenNetworkManagementVpcFlowLogsConfigState(res["state"], d, config)); err != nil { + return fmt.Errorf("Error reading VpcFlowLogsConfig: %s", err) + } + if err := d.Set("aggregation_interval", flattenNetworkManagementVpcFlowLogsConfigAggregationInterval(res["aggregationInterval"], d, config)); err != nil { + return fmt.Errorf("Error reading VpcFlowLogsConfig: %s", err) + } + if err := d.Set("flow_sampling", flattenNetworkManagementVpcFlowLogsConfigFlowSampling(res["flowSampling"], d, config)); err != nil { + return fmt.Errorf("Error reading VpcFlowLogsConfig: %s", err) + } + if err := d.Set("metadata", flattenNetworkManagementVpcFlowLogsConfigMetadata(res["metadata"], d, config)); err != nil { + return fmt.Errorf("Error reading VpcFlowLogsConfig: %s", err) + } + if err := d.Set("metadata_fields", flattenNetworkManagementVpcFlowLogsConfigMetadataFields(res["metadataFields"], d, config)); err != nil { + return fmt.Errorf("Error reading VpcFlowLogsConfig: %s", err) + } + if err := d.Set("filter_expr", flattenNetworkManagementVpcFlowLogsConfigFilterExpr(res["filterExpr"], d, config)); err != nil { + return fmt.Errorf("Error reading VpcFlowLogsConfig: %s", err) + } + if err := d.Set("interconnect_attachment", flattenNetworkManagementVpcFlowLogsConfigInterconnectAttachment(res["interconnectAttachment"], d, config)); err != nil { + return fmt.Errorf("Error reading VpcFlowLogsConfig: %s", err) + } + if err := d.Set("vpn_tunnel", flattenNetworkManagementVpcFlowLogsConfigVpnTunnel(res["vpnTunnel"], d, config)); err != nil { + return fmt.Errorf("Error reading VpcFlowLogsConfig: %s", err) + } + if err := d.Set("labels", flattenNetworkManagementVpcFlowLogsConfigLabels(res["labels"], d, config)); err != nil { + return fmt.Errorf("Error reading VpcFlowLogsConfig: %s", err) + } + if err := d.Set("create_time", flattenNetworkManagementVpcFlowLogsConfigCreateTime(res["createTime"], d, config)); err != nil { + return fmt.Errorf("Error reading VpcFlowLogsConfig: %s", err) + } + if err := d.Set("update_time", flattenNetworkManagementVpcFlowLogsConfigUpdateTime(res["updateTime"], d, config)); err != nil { + return fmt.Errorf("Error reading VpcFlowLogsConfig: %s", err) + } + if err := d.Set("terraform_labels", flattenNetworkManagementVpcFlowLogsConfigTerraformLabels(res["labels"], d, config)); err != nil { + return fmt.Errorf("Error reading VpcFlowLogsConfig: %s", err) + } + if err := d.Set("effective_labels", flattenNetworkManagementVpcFlowLogsConfigEffectiveLabels(res["labels"], d, config)); err != nil { + return fmt.Errorf("Error reading VpcFlowLogsConfig: %s", err) + } + + return nil +} + +func resourceNetworkManagementVpcFlowLogsConfigUpdate(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 VpcFlowLogsConfig: %s", err) + } + billingProject = project + + obj := make(map[string]interface{}) + descriptionProp, err := expandNetworkManagementVpcFlowLogsConfigDescription(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 + } + stateProp, err := expandNetworkManagementVpcFlowLogsConfigState(d.Get("state"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("state"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, stateProp)) { + obj["state"] = stateProp + } + aggregationIntervalProp, err := expandNetworkManagementVpcFlowLogsConfigAggregationInterval(d.Get("aggregation_interval"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("aggregation_interval"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, aggregationIntervalProp)) { + obj["aggregationInterval"] = aggregationIntervalProp + } + flowSamplingProp, err := expandNetworkManagementVpcFlowLogsConfigFlowSampling(d.Get("flow_sampling"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("flow_sampling"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, flowSamplingProp)) { + obj["flowSampling"] = flowSamplingProp + } + metadataProp, err := expandNetworkManagementVpcFlowLogsConfigMetadata(d.Get("metadata"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("metadata"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, metadataProp)) { + obj["metadata"] = metadataProp + } + metadataFieldsProp, err := expandNetworkManagementVpcFlowLogsConfigMetadataFields(d.Get("metadata_fields"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("metadata_fields"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, metadataFieldsProp)) { + obj["metadataFields"] = metadataFieldsProp + } + filterExprProp, err := expandNetworkManagementVpcFlowLogsConfigFilterExpr(d.Get("filter_expr"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("filter_expr"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, filterExprProp)) { + obj["filterExpr"] = filterExprProp + } + interconnectAttachmentProp, err := expandNetworkManagementVpcFlowLogsConfigInterconnectAttachment(d.Get("interconnect_attachment"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("interconnect_attachment"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, interconnectAttachmentProp)) { + obj["interconnectAttachment"] = interconnectAttachmentProp + } + vpnTunnelProp, err := expandNetworkManagementVpcFlowLogsConfigVpnTunnel(d.Get("vpn_tunnel"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("vpn_tunnel"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, vpnTunnelProp)) { + obj["vpnTunnel"] = vpnTunnelProp + } + labelsProp, err := expandNetworkManagementVpcFlowLogsConfigEffectiveLabels(d.Get("effective_labels"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("effective_labels"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, labelsProp)) { + obj["labels"] = labelsProp + } + + url, err := tpgresource.ReplaceVars(d, config, "{{NetworkManagementBasePath}}projects/{{project}}/locations/{{location}}/vpcFlowLogsConfigs/{{vpc_flow_logs_config_id}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Updating VpcFlowLogsConfig %q: %#v", d.Id(), obj) + headers := make(http.Header) + updateMask := []string{} + + if d.HasChange("description") { + updateMask = append(updateMask, "description") + } + + if d.HasChange("state") { + updateMask = append(updateMask, "state") + } + + if d.HasChange("aggregation_interval") { + updateMask = append(updateMask, "aggregationInterval") + } + + if d.HasChange("flow_sampling") { + updateMask = append(updateMask, "flowSampling") + } + + if d.HasChange("metadata") { + updateMask = append(updateMask, "metadata") + } + + if d.HasChange("metadata_fields") { + updateMask = append(updateMask, "metadataFields") + } + + if d.HasChange("filter_expr") { + updateMask = append(updateMask, "filterExpr") + } + + if d.HasChange("interconnect_attachment") { + updateMask = append(updateMask, "interconnectAttachment") + } + + if d.HasChange("vpn_tunnel") { + updateMask = append(updateMask, "vpnTunnel") + } + + if d.HasChange("effective_labels") { + updateMask = append(updateMask, "labels") + } + // 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 VpcFlowLogsConfig %q: %s", d.Id(), err) + } else { + log.Printf("[DEBUG] Finished updating VpcFlowLogsConfig %q: %#v", d.Id(), res) + } + + err = NetworkManagementOperationWaitTime( + config, res, project, "Updating VpcFlowLogsConfig", userAgent, + d.Timeout(schema.TimeoutUpdate)) + + if err != nil { + return err + } + } + + return resourceNetworkManagementVpcFlowLogsConfigRead(d, meta) +} + +func resourceNetworkManagementVpcFlowLogsConfigDelete(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 VpcFlowLogsConfig: %s", err) + } + billingProject = project + + url, err := tpgresource.ReplaceVars(d, config, "{{NetworkManagementBasePath}}projects/{{project}}/locations/{{location}}/vpcFlowLogsConfigs/{{vpc_flow_logs_config_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 VpcFlowLogsConfig %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, "VpcFlowLogsConfig") + } + + err = NetworkManagementOperationWaitTime( + config, res, project, "Deleting VpcFlowLogsConfig", userAgent, + d.Timeout(schema.TimeoutDelete)) + + if err != nil { + return err + } + + log.Printf("[DEBUG] Finished deleting VpcFlowLogsConfig %q: %#v", d.Id(), res) + return nil +} + +func resourceNetworkManagementVpcFlowLogsConfigImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + config := meta.(*transport_tpg.Config) + if err := tpgresource.ParseImportId([]string{ + "^projects/(?P[^/]+)/locations/(?P[^/]+)/vpcFlowLogsConfigs/(?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}}/vpcFlowLogsConfigs/{{vpc_flow_logs_config_id}}") + if err != nil { + return nil, fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + return []*schema.ResourceData{d}, nil +} + +func flattenNetworkManagementVpcFlowLogsConfigName(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkManagementVpcFlowLogsConfigDescription(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkManagementVpcFlowLogsConfigState(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkManagementVpcFlowLogsConfigAggregationInterval(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkManagementVpcFlowLogsConfigFlowSampling(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkManagementVpcFlowLogsConfigMetadata(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkManagementVpcFlowLogsConfigMetadataFields(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkManagementVpcFlowLogsConfigFilterExpr(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkManagementVpcFlowLogsConfigInterconnectAttachment(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkManagementVpcFlowLogsConfigVpnTunnel(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkManagementVpcFlowLogsConfigLabels(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + if v == nil { + return v + } + + transformed := make(map[string]interface{}) + if l, ok := d.GetOkExists("labels"); ok { + for k := range l.(map[string]interface{}) { + transformed[k] = v.(map[string]interface{})[k] + } + } + + return transformed +} + +func flattenNetworkManagementVpcFlowLogsConfigCreateTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkManagementVpcFlowLogsConfigUpdateTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkManagementVpcFlowLogsConfigTerraformLabels(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + if v == nil { + return v + } + + transformed := make(map[string]interface{}) + if l, ok := d.GetOkExists("terraform_labels"); ok { + for k := range l.(map[string]interface{}) { + transformed[k] = v.(map[string]interface{})[k] + } + } + + return transformed +} + +func flattenNetworkManagementVpcFlowLogsConfigEffectiveLabels(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func expandNetworkManagementVpcFlowLogsConfigDescription(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandNetworkManagementVpcFlowLogsConfigState(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandNetworkManagementVpcFlowLogsConfigAggregationInterval(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandNetworkManagementVpcFlowLogsConfigFlowSampling(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandNetworkManagementVpcFlowLogsConfigMetadata(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandNetworkManagementVpcFlowLogsConfigMetadataFields(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandNetworkManagementVpcFlowLogsConfigFilterExpr(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandNetworkManagementVpcFlowLogsConfigInterconnectAttachment(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandNetworkManagementVpcFlowLogsConfigVpnTunnel(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandNetworkManagementVpcFlowLogsConfigEffectiveLabels(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (map[string]string, error) { + if v == nil { + return map[string]string{}, nil + } + m := make(map[string]string) + for k, val := range v.(map[string]interface{}) { + m[k] = val.(string) + } + return m, nil +} diff --git a/google/services/networkmanagement/resource_network_management_vpc_flow_logs_config_generated_meta.yaml b/google/services/networkmanagement/resource_network_management_vpc_flow_logs_config_generated_meta.yaml new file mode 100644 index 00000000000..a687a695107 --- /dev/null +++ b/google/services/networkmanagement/resource_network_management_vpc_flow_logs_config_generated_meta.yaml @@ -0,0 +1,5 @@ +resource: 'google_network_management_vpc_flow_logs_config' +generation_type: 'mmv1' +api_service_name: 'networkmanagement.googleapis.com' +api_version: 'v1' +api_resource_type_kind: 'VpcFlowLogsConfig' diff --git a/google/services/networkmanagement/resource_network_management_vpc_flow_logs_config_generated_test.go b/google/services/networkmanagement/resource_network_management_vpc_flow_logs_config_generated_test.go new file mode 100644 index 00000000000..96ccbf63fd1 --- /dev/null +++ b/google/services/networkmanagement/resource_network_management_vpc_flow_logs_config_generated_test.go @@ -0,0 +1,388 @@ +// 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 networkmanagement_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/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" +) + +func TestAccNetworkManagementVpcFlowLogsConfig_networkManagementVpcFlowLogsConfigInterconnectFullExample(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": acctest.RandString(t, 10), + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckNetworkManagementVpcFlowLogsConfigDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccNetworkManagementVpcFlowLogsConfig_networkManagementVpcFlowLogsConfigInterconnectFullExample(context), + }, + { + ResourceName: "google_network_management_vpc_flow_logs_config.interconnect-test", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"labels", "location", "terraform_labels", "vpc_flow_logs_config_id"}, + }, + }, + }) +} + +func testAccNetworkManagementVpcFlowLogsConfig_networkManagementVpcFlowLogsConfigInterconnectFullExample(context map[string]interface{}) string { + return acctest.Nprintf(` +data "google_project" "project" { +} + +resource "google_network_management_vpc_flow_logs_config" "interconnect-test" { + vpc_flow_logs_config_id = "tf-test-full-interconnect-test-id%{random_suffix}" + location = "global" + interconnect_attachment = "projects/${data.google_project.project.number}/regions/us-east4/interconnectAttachments/${google_compute_interconnect_attachment.attachment.name}" + state = "ENABLED" + aggregation_interval = "INTERVAL_5_SEC" + description = "VPC Flow Logs over a VPN Gateway." + flow_sampling = 0.5 + metadata = "INCLUDE_ALL_METADATA" +} + +resource "google_compute_network" "network" { + name = "tf-test-full-interconnect-test-network%{random_suffix}" +} + +resource "google_compute_router" "router" { + name = "tf-test-full-interconnect-test-router%{random_suffix}" + network = google_compute_network.network.name + bgp { + asn = 16550 + } +} + +resource "google_compute_interconnect_attachment" "attachment" { + name = "tf-test-full-interconnect-test-id%{random_suffix}" + edge_availability_domain = "AVAILABILITY_DOMAIN_1" + type = "PARTNER" + router = google_compute_router.router.id + mtu = 1500 +} + +`, context) +} + +func TestAccNetworkManagementVpcFlowLogsConfig_networkManagementVpcFlowLogsConfigInterconnectBasicExample(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": acctest.RandString(t, 10), + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckNetworkManagementVpcFlowLogsConfigDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccNetworkManagementVpcFlowLogsConfig_networkManagementVpcFlowLogsConfigInterconnectBasicExample(context), + }, + { + ResourceName: "google_network_management_vpc_flow_logs_config.interconnect-test", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"labels", "location", "terraform_labels", "vpc_flow_logs_config_id"}, + }, + }, + }) +} + +func testAccNetworkManagementVpcFlowLogsConfig_networkManagementVpcFlowLogsConfigInterconnectBasicExample(context map[string]interface{}) string { + return acctest.Nprintf(` +data "google_project" "project" { +} + +resource "google_network_management_vpc_flow_logs_config" "interconnect-test" { + vpc_flow_logs_config_id = "tf-test-basic-interconnect-test-id%{random_suffix}" + location = "global" + interconnect_attachment = "projects/${data.google_project.project.number}/regions/us-east4/interconnectAttachments/${google_compute_interconnect_attachment.attachment.name}" +} + +resource "google_compute_network" "network" { + name = "tf-test-basic-interconnect-test-network%{random_suffix}" +} + +resource "google_compute_router" "router" { + name = "tf-test-basic-interconnect-test-router%{random_suffix}" + network = google_compute_network.network.name + bgp { + asn = 16550 + } +} + +resource "google_compute_interconnect_attachment" "attachment" { + name = "tf-test-basic-interconnect-test-id%{random_suffix}" + edge_availability_domain = "AVAILABILITY_DOMAIN_1" + type = "PARTNER" + router = google_compute_router.router.id + mtu = 1500 +} + +`, context) +} + +func TestAccNetworkManagementVpcFlowLogsConfig_networkManagementVpcFlowLogsConfigVpnBasicExample(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": acctest.RandString(t, 10), + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckNetworkManagementVpcFlowLogsConfigDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccNetworkManagementVpcFlowLogsConfig_networkManagementVpcFlowLogsConfigVpnBasicExample(context), + }, + { + ResourceName: "google_network_management_vpc_flow_logs_config.vpn-test", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"labels", "location", "terraform_labels", "vpc_flow_logs_config_id"}, + }, + }, + }) +} + +func testAccNetworkManagementVpcFlowLogsConfig_networkManagementVpcFlowLogsConfigVpnBasicExample(context map[string]interface{}) string { + return acctest.Nprintf(` +data "google_project" "project" { +} + +resource "google_network_management_vpc_flow_logs_config" "vpn-test" { + vpc_flow_logs_config_id = "tf-test-basic-test-id%{random_suffix}" + location = "global" + vpn_tunnel = "projects/${data.google_project.project.number}/regions/us-central1/vpnTunnels/${google_compute_vpn_tunnel.tunnel.name}" +} + +resource "google_compute_vpn_tunnel" "tunnel" { + name = "tf-test-basic-test-tunnel%{random_suffix}" + peer_ip = "15.0.0.120" + shared_secret = "a secret message" + target_vpn_gateway = google_compute_vpn_gateway.target_gateway.id + + depends_on = [ + google_compute_forwarding_rule.fr_esp, + google_compute_forwarding_rule.fr_udp500, + google_compute_forwarding_rule.fr_udp4500, + ] +} + +resource "google_compute_vpn_gateway" "target_gateway" { + name = "tf-test-basic-test-gateway%{random_suffix}" + network = google_compute_network.network.id +} + +resource "google_compute_network" "network" { + name = "tf-test-basic-test-network%{random_suffix}" +} + +resource "google_compute_address" "vpn_static_ip" { + name = "tf-test-basic-test-address%{random_suffix}" +} + +resource "google_compute_forwarding_rule" "fr_esp" { + name = "tf-test-basic-test-fresp%{random_suffix}" + ip_protocol = "ESP" + ip_address = google_compute_address.vpn_static_ip.address + target = google_compute_vpn_gateway.target_gateway.id +} + +resource "google_compute_forwarding_rule" "fr_udp500" { + name = "tf-test-basic-test-fr500%{random_suffix}" + ip_protocol = "UDP" + port_range = "500" + ip_address = google_compute_address.vpn_static_ip.address + target = google_compute_vpn_gateway.target_gateway.id +} + +resource "google_compute_forwarding_rule" "fr_udp4500" { + name = "tf-test-basic-test-fr4500%{random_suffix}" + ip_protocol = "UDP" + port_range = "4500" + ip_address = google_compute_address.vpn_static_ip.address + target = google_compute_vpn_gateway.target_gateway.id +} + +resource "google_compute_route" "route" { + name = "tf-test-basic-test-route%{random_suffix}" + network = google_compute_network.network.name + dest_range = "15.0.0.0/24" + priority = 1000 + next_hop_vpn_tunnel = google_compute_vpn_tunnel.tunnel.id +} +`, context) +} + +func TestAccNetworkManagementVpcFlowLogsConfig_networkManagementVpcFlowLogsConfigVpnFullExample(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": acctest.RandString(t, 10), + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckNetworkManagementVpcFlowLogsConfigDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccNetworkManagementVpcFlowLogsConfig_networkManagementVpcFlowLogsConfigVpnFullExample(context), + }, + { + ResourceName: "google_network_management_vpc_flow_logs_config.vpn-test", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"labels", "location", "terraform_labels", "vpc_flow_logs_config_id"}, + }, + }, + }) +} + +func testAccNetworkManagementVpcFlowLogsConfig_networkManagementVpcFlowLogsConfigVpnFullExample(context map[string]interface{}) string { + return acctest.Nprintf(` +data "google_project" "project" { +} + +resource "google_network_management_vpc_flow_logs_config" "vpn-test" { + vpc_flow_logs_config_id = "tf-test-full-test-id%{random_suffix}" + location = "global" + vpn_tunnel = "projects/${data.google_project.project.number}/regions/us-central1/vpnTunnels/${google_compute_vpn_tunnel.tunnel.name}" + state = "ENABLED" + aggregation_interval = "INTERVAL_5_SEC" + description = "VPC Flow Logs over a VPN Gateway." + flow_sampling = 0.5 + metadata = "INCLUDE_ALL_METADATA" +} + +resource "google_compute_vpn_tunnel" "tunnel" { + name = "tf-test-full-test-tunnel%{random_suffix}" + peer_ip = "15.0.0.120" + shared_secret = "a secret message" + target_vpn_gateway = google_compute_vpn_gateway.target_gateway.id + + depends_on = [ + google_compute_forwarding_rule.fr_esp, + google_compute_forwarding_rule.fr_udp500, + google_compute_forwarding_rule.fr_udp4500, + ] +} + +resource "google_compute_vpn_gateway" "target_gateway" { + name = "tf-test-full-test-gateway%{random_suffix}" + network = google_compute_network.network.id +} + +resource "google_compute_network" "network" { + name = "tf-test-full-test-network%{random_suffix}" +} + +resource "google_compute_address" "vpn_static_ip" { + name = "tf-test-full-test-address%{random_suffix}" +} + +resource "google_compute_forwarding_rule" "fr_esp" { + name = "tf-test-full-test-fresp%{random_suffix}" + ip_protocol = "ESP" + ip_address = google_compute_address.vpn_static_ip.address + target = google_compute_vpn_gateway.target_gateway.id +} + +resource "google_compute_forwarding_rule" "fr_udp500" { + name = "tf-test-full-test-fr500%{random_suffix}" + ip_protocol = "UDP" + port_range = "500" + ip_address = google_compute_address.vpn_static_ip.address + target = google_compute_vpn_gateway.target_gateway.id +} + +resource "google_compute_forwarding_rule" "fr_udp4500" { + name = "tf-test-full-test-fr4500%{random_suffix}" + ip_protocol = "UDP" + port_range = "4500" + ip_address = google_compute_address.vpn_static_ip.address + target = google_compute_vpn_gateway.target_gateway.id +} + +resource "google_compute_route" "route" { + name = "tf-test-full-test-route%{random_suffix}" + network = google_compute_network.network.name + dest_range = "15.0.0.0/24" + priority = 1000 + next_hop_vpn_tunnel = google_compute_vpn_tunnel.tunnel.id +} +`, context) +} + +func testAccCheckNetworkManagementVpcFlowLogsConfigDestroyProducer(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_network_management_vpc_flow_logs_config" { + continue + } + if strings.HasPrefix(name, "data.") { + continue + } + + config := acctest.GoogleProviderConfig(t) + + url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{NetworkManagementBasePath}}projects/{{project}}/locations/{{location}}/vpcFlowLogsConfigs/{{vpc_flow_logs_config_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("NetworkManagementVpcFlowLogsConfig still exists at %s", url) + } + } + + return nil + } +} diff --git a/google/services/networkmanagement/resource_network_management_vpc_flow_logs_config_sweeper.go b/google/services/networkmanagement/resource_network_management_vpc_flow_logs_config_sweeper.go new file mode 100644 index 00000000000..dd0c5804bee --- /dev/null +++ b/google/services/networkmanagement/resource_network_management_vpc_flow_logs_config_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 networkmanagement + +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("NetworkManagementVpcFlowLogsConfig", testSweepNetworkManagementVpcFlowLogsConfig) +} + +// At the time of writing, the CI only passes us-central1 as the region +func testSweepNetworkManagementVpcFlowLogsConfig(region string) error { + resourceName := "NetworkManagementVpcFlowLogsConfig" + 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://networkmanagement.googleapis.com/v1/projects/{{project}}/locations/{{location}}/vpcFlowLogsConfigs", "?")[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["vpcFlowLogsConfigs"] + 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://networkmanagement.googleapis.com/v1/projects/{{project}}/locations/{{location}}/vpcFlowLogsConfigs/{{vpc_flow_logs_config_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/services/networkmanagement/resource_network_management_vpc_flow_logs_config_test.go b/google/services/networkmanagement/resource_network_management_vpc_flow_logs_config_test.go index e058e019080..bb3427bf716 100644 --- a/google/services/networkmanagement/resource_network_management_vpc_flow_logs_config_test.go +++ b/google/services/networkmanagement/resource_network_management_vpc_flow_logs_config_test.go @@ -1,3 +1,246 @@ // Copyright (c) HashiCorp, Inc. // SPDX-License-Identifier: MPL-2.0 package networkmanagement_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-provider-google/google/acctest" +) + +func TestAccNetworkManagementVpcFlowLogsConfig_updateInterconnect(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": acctest.RandString(t, 10), + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckNetworkManagementVpcFlowLogsConfigDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccNetworkManagementVpcFlowLogsConfig_fullInterconnect(context), + }, + { + ResourceName: "google_network_management_vpc_flow_logs_config.interconnect-test", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"labels", "location", "terraform_labels", "vpc_flow_logs_config_id"}, + }, + { + Config: testAccNetworkManagementVpcFlowLogsConfig_updateInterconnect(context), + }, + { + ResourceName: "google_network_management_vpc_flow_logs_config.interconnect-test", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"labels", "location", "terraform_labels", "vpc_flow_logs_config_id"}, + }, + }, + }) +} + +func testAccNetworkManagementVpcFlowLogsConfig_fullInterconnect(context map[string]interface{}) string { + return acctest.Nprintf(` +data "google_project" "project" { +} + +resource "google_network_management_vpc_flow_logs_config" "interconnect-test" { + vpc_flow_logs_config_id = "tf-test-full-interconnect-test-id%{random_suffix}" + location = "global" + interconnect_attachment = "projects/${data.google_project.project.number}/regions/us-east4/interconnectAttachments/${google_compute_interconnect_attachment.attachment.name}" +} + +resource "google_compute_network" "network" { + name = "tf-test-full-interconnect-test-network%{random_suffix}" +} + +resource "google_compute_router" "router" { + name = "tf-test-full-interconnect-test-router%{random_suffix}" + network = google_compute_network.network.name + bgp { + asn = 16550 + } +} + +resource "google_compute_interconnect_attachment" "attachment" { + name = "tf-test-full-interconnect-test-id%{random_suffix}" + edge_availability_domain = "AVAILABILITY_DOMAIN_1" + type = "PARTNER" + router = google_compute_router.router.id + mtu = 1500 +} + +`, context) +} + +func testAccNetworkManagementVpcFlowLogsConfig_updateInterconnect(context map[string]interface{}) string { + return acctest.Nprintf(` +data "google_project" "project" { +} + +resource "google_network_management_vpc_flow_logs_config" "interconnect-test" { + vpc_flow_logs_config_id = "tf-test-full-interconnect-test-id%{random_suffix}" + location = "global" + interconnect_attachment = "projects/${data.google_project.project.number}/regions/us-east4/interconnectAttachments/${google_compute_interconnect_attachment.attachment.name}" + state = "DISABLED" + aggregation_interval = "INTERVAL_30_SEC" + description = "This is an updated description" + flow_sampling = 0.5 + metadata = "EXCLUDE_ALL_METADATA" +} + +resource "google_compute_network" "network" { + name = "tf-test-full-interconnect-test-network%{random_suffix}" +} + +resource "google_compute_router" "router" { + name = "tf-test-full-interconnect-test-router%{random_suffix}" + network = google_compute_network.network.name + bgp { + asn = 16550 + } +} + +resource "google_compute_interconnect_attachment" "attachment" { + name = "tf-test-full-interconnect-test-id%{random_suffix}" + edge_availability_domain = "AVAILABILITY_DOMAIN_1" + type = "PARTNER" + router = google_compute_router.router.id + mtu = 1500 +} + +`, context) +} + +func TestAccNetworkManagementVpcFlowLogsConfig_updateVpn(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": acctest.RandString(t, 10), + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckNetworkManagementVpcFlowLogsConfigDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccNetworkManagementVpcFlowLogsConfig_fullVpn(context), + }, + { + ResourceName: "google_network_management_vpc_flow_logs_config.example", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"labels", "location", "terraform_labels", "vpc_flow_logs_config_id"}, + }, + { + Config: testAccNetworkManagementVpcFlowLogsConfig_updateVpn(context), + }, + { + ResourceName: "google_network_management_vpc_flow_logs_config.example", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"labels", "location", "terraform_labels", "vpc_flow_logs_config_id"}, + }, + }, + }) +} + +func testAccNetworkManagementVpcFlowLogsConfig_fullVpn(context map[string]interface{}) string { + vpcFlowLogsCfg := acctest.Nprintf(` +data "google_project" "project" { +} + +resource "google_network_management_vpc_flow_logs_config" "example" { + vpc_flow_logs_config_id = "id-example-%{random_suffix}" + location = "global" + vpn_tunnel = "projects/${data.google_project.project.number}/regions/us-central1/vpnTunnels/${google_compute_vpn_tunnel.tunnel.name}" +} +`, context) + return fmt.Sprintf("%s\n\n%s\n\n", vpcFlowLogsCfg, testAccNetworkManagementVpcFlowLogsConfig_baseResources(context)) +} + +func testAccNetworkManagementVpcFlowLogsConfig_updateVpn(context map[string]interface{}) string { + vpcFlowLogsCfg := acctest.Nprintf(` +data "google_project" "project" { +} + +resource "google_network_management_vpc_flow_logs_config" "example" { + vpc_flow_logs_config_id = "id-example-%{random_suffix}" + location = "global" + vpn_tunnel = "projects/${data.google_project.project.number}/regions/us-central1/vpnTunnels/${google_compute_vpn_tunnel.tunnel.name}" + state = "DISABLED" + aggregation_interval = "INTERVAL_30_SEC" + description = "This is an updated description" + flow_sampling = 0.5 + metadata = "EXCLUDE_ALL_METADATA" +} +`, context) + return fmt.Sprintf("%s\n\n%s\n\n", vpcFlowLogsCfg, testAccNetworkManagementVpcFlowLogsConfig_baseResources(context)) +} + +func testAccNetworkManagementVpcFlowLogsConfig_baseResources(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_compute_vpn_tunnel" "tunnel" { + name = "tf-test-example-tunnel%{random_suffix}" + peer_ip = "15.0.0.120" + shared_secret = "a secret message" + target_vpn_gateway = google_compute_vpn_gateway.target_gateway.id + + depends_on = [ + google_compute_forwarding_rule.fr_esp, + google_compute_forwarding_rule.fr_udp500, + google_compute_forwarding_rule.fr_udp4500, + ] +} + +resource "google_compute_vpn_gateway" "target_gateway" { + name = "tf-test-example-gateway%{random_suffix}" + network = google_compute_network.network.id +} + +resource "google_compute_network" "network" { + name = "tf-test-example-network%{random_suffix}" +} + +resource "google_compute_address" "vpn_static_ip" { + name = "tf-test-example-address%{random_suffix}" +} + +resource "google_compute_forwarding_rule" "fr_esp" { + name = "tf-test-example-fresp%{random_suffix}" + ip_protocol = "ESP" + ip_address = google_compute_address.vpn_static_ip.address + target = google_compute_vpn_gateway.target_gateway.id +} + +resource "google_compute_forwarding_rule" "fr_udp500" { + name = "tf-test-example-fr500%{random_suffix}" + ip_protocol = "UDP" + port_range = "500" + ip_address = google_compute_address.vpn_static_ip.address + target = google_compute_vpn_gateway.target_gateway.id +} + +resource "google_compute_forwarding_rule" "fr_udp4500" { + name = "tf-test-example-fr4500%{random_suffix}" + ip_protocol = "UDP" + port_range = "4500" + ip_address = google_compute_address.vpn_static_ip.address + target = google_compute_vpn_gateway.target_gateway.id +} + +resource "google_compute_route" "route" { + name = "tf-test-example-route%{random_suffix}" + network = google_compute_network.network.name + dest_range = "15.0.0.0/24" + priority = 1000 + next_hop_vpn_tunnel = google_compute_vpn_tunnel.tunnel.id +} +`, context) +} diff --git a/website/docs/r/network_management_vpc_flow_logs_config.html.markdown b/website/docs/r/network_management_vpc_flow_logs_config.html.markdown index 5418bcfb0df..073dca7ea95 100644 --- a/website/docs/r/network_management_vpc_flow_logs_config.html.markdown +++ b/website/docs/r/network_management_vpc_flow_logs_config.html.markdown @@ -21,8 +21,6 @@ description: |- VPC Flow Logs Config is a resource that lets you configure Flow Logs for VPC, Interconnect attachments or VPN Tunnels. -~> **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.
@@ -35,11 +33,9 @@ See [Provider Versions](https://terraform.io/docs/providers/google/guides/provid ```hcl data "google_project" "project" { - provider = google-beta } resource "google_network_management_vpc_flow_logs_config" "interconnect-test" { - provider = google-beta vpc_flow_logs_config_id = "full-interconnect-test-id" location = "global" interconnect_attachment = "projects/${data.google_project.project.number}/regions/us-east4/interconnectAttachments/${google_compute_interconnect_attachment.attachment.name}" @@ -51,12 +47,10 @@ resource "google_network_management_vpc_flow_logs_config" "interconnect-test" { } resource "google_compute_network" "network" { - provider = google-beta name = "full-interconnect-test-network" } resource "google_compute_router" "router" { - provider = google-beta name = "full-interconnect-test-router" network = google_compute_network.network.name bgp { @@ -65,7 +59,6 @@ resource "google_compute_router" "router" { } resource "google_compute_interconnect_attachment" "attachment" { - provider = google-beta name = "full-interconnect-test-id" edge_availability_domain = "AVAILABILITY_DOMAIN_1" type = "PARTNER" @@ -84,23 +77,19 @@ resource "google_compute_interconnect_attachment" "attachment" { ```hcl data "google_project" "project" { - provider = google-beta } resource "google_network_management_vpc_flow_logs_config" "interconnect-test" { - provider = google-beta vpc_flow_logs_config_id = "basic-interconnect-test-id" location = "global" interconnect_attachment = "projects/${data.google_project.project.number}/regions/us-east4/interconnectAttachments/${google_compute_interconnect_attachment.attachment.name}" } resource "google_compute_network" "network" { - provider = google-beta name = "basic-interconnect-test-network" } resource "google_compute_router" "router" { - provider = google-beta name = "basic-interconnect-test-router" network = google_compute_network.network.name bgp { @@ -109,7 +98,6 @@ resource "google_compute_router" "router" { } resource "google_compute_interconnect_attachment" "attachment" { - provider = google-beta name = "basic-interconnect-test-id" edge_availability_domain = "AVAILABILITY_DOMAIN_1" type = "PARTNER" @@ -128,18 +116,15 @@ resource "google_compute_interconnect_attachment" "attachment" { ```hcl data "google_project" "project" { - provider = google-beta } resource "google_network_management_vpc_flow_logs_config" "vpn-test" { - provider = google-beta vpc_flow_logs_config_id = "basic-test-id" location = "global" vpn_tunnel = "projects/${data.google_project.project.number}/regions/us-central1/vpnTunnels/${google_compute_vpn_tunnel.tunnel.name}" } resource "google_compute_vpn_tunnel" "tunnel" { - provider = google-beta name = "basic-test-tunnel" peer_ip = "15.0.0.120" shared_secret = "a secret message" @@ -153,23 +138,19 @@ resource "google_compute_vpn_tunnel" "tunnel" { } resource "google_compute_vpn_gateway" "target_gateway" { - provider = google-beta name = "basic-test-gateway" network = google_compute_network.network.id } resource "google_compute_network" "network" { - provider = google-beta name = "basic-test-network" } resource "google_compute_address" "vpn_static_ip" { - provider = google-beta name = "basic-test-address" } resource "google_compute_forwarding_rule" "fr_esp" { - provider = google-beta name = "basic-test-fresp" ip_protocol = "ESP" ip_address = google_compute_address.vpn_static_ip.address @@ -177,7 +158,6 @@ resource "google_compute_forwarding_rule" "fr_esp" { } resource "google_compute_forwarding_rule" "fr_udp500" { - provider = google-beta name = "basic-test-fr500" ip_protocol = "UDP" port_range = "500" @@ -186,7 +166,6 @@ resource "google_compute_forwarding_rule" "fr_udp500" { } resource "google_compute_forwarding_rule" "fr_udp4500" { - provider = google-beta name = "basic-test-fr4500" ip_protocol = "UDP" port_range = "4500" @@ -195,7 +174,6 @@ resource "google_compute_forwarding_rule" "fr_udp4500" { } resource "google_compute_route" "route" { - provider = google-beta name = "basic-test-route" network = google_compute_network.network.name dest_range = "15.0.0.0/24" @@ -213,11 +191,9 @@ resource "google_compute_route" "route" { ```hcl data "google_project" "project" { - provider = google-beta } resource "google_network_management_vpc_flow_logs_config" "vpn-test" { - provider = google-beta vpc_flow_logs_config_id = "full-test-id" location = "global" vpn_tunnel = "projects/${data.google_project.project.number}/regions/us-central1/vpnTunnels/${google_compute_vpn_tunnel.tunnel.name}" @@ -229,7 +205,6 @@ resource "google_network_management_vpc_flow_logs_config" "vpn-test" { } resource "google_compute_vpn_tunnel" "tunnel" { - provider = google-beta name = "full-test-tunnel" peer_ip = "15.0.0.120" shared_secret = "a secret message" @@ -243,23 +218,19 @@ resource "google_compute_vpn_tunnel" "tunnel" { } resource "google_compute_vpn_gateway" "target_gateway" { - provider = google-beta name = "full-test-gateway" network = google_compute_network.network.id } resource "google_compute_network" "network" { - provider = google-beta name = "full-test-network" } resource "google_compute_address" "vpn_static_ip" { - provider = google-beta name = "full-test-address" } resource "google_compute_forwarding_rule" "fr_esp" { - provider = google-beta name = "full-test-fresp" ip_protocol = "ESP" ip_address = google_compute_address.vpn_static_ip.address @@ -267,7 +238,6 @@ resource "google_compute_forwarding_rule" "fr_esp" { } resource "google_compute_forwarding_rule" "fr_udp500" { - provider = google-beta name = "full-test-fr500" ip_protocol = "UDP" port_range = "500" @@ -276,7 +246,6 @@ resource "google_compute_forwarding_rule" "fr_udp500" { } resource "google_compute_forwarding_rule" "fr_udp4500" { - provider = google-beta name = "full-test-fr4500" ip_protocol = "UDP" port_range = "4500" @@ -285,7 +254,6 @@ resource "google_compute_forwarding_rule" "fr_udp4500" { } resource "google_compute_route" "route" { - provider = google-beta name = "full-test-route" network = google_compute_network.network.name dest_range = "15.0.0.0/24"