diff --git a/.changelog/9815.txt b/.changelog/9815.txt new file mode 100644 index 0000000000..2d6e310a6a --- /dev/null +++ b/.changelog/9815.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +networksecurity: new `google_network_security_firewall_endpoint_association` resource +``` \ No newline at end of file diff --git a/google-beta/provider/provider_mmv1_resources.go b/google-beta/provider/provider_mmv1_resources.go index 8da3d67af7..0774729561 100644 --- a/google-beta/provider/provider_mmv1_resources.go +++ b/google-beta/provider/provider_mmv1_resources.go @@ -434,9 +434,9 @@ var handwrittenIAMDatasources = map[string]*schema.Resource{ } // Resources -// Generated resources: 449 +// Generated resources: 450 // Generated IAM resources: 267 -// Total generated resources: 716 +// Total generated resources: 717 var generatedResources = map[string]*schema.Resource{ "google_folder_access_approval_settings": accessapproval.ResourceAccessApprovalFolderSettings(), "google_organization_access_approval_settings": accessapproval.ResourceAccessApprovalOrganizationSettings(), @@ -980,6 +980,7 @@ var generatedResources = map[string]*schema.Resource{ "google_network_security_authorization_policy": networksecurity.ResourceNetworkSecurityAuthorizationPolicy(), "google_network_security_client_tls_policy": networksecurity.ResourceNetworkSecurityClientTlsPolicy(), "google_network_security_firewall_endpoint": networksecurity.ResourceNetworkSecurityFirewallEndpoint(), + "google_network_security_firewall_endpoint_association": networksecurity.ResourceNetworkSecurityFirewallEndpointAssociation(), "google_network_security_gateway_security_policy": networksecurity.ResourceNetworkSecurityGatewaySecurityPolicy(), "google_network_security_gateway_security_policy_rule": networksecurity.ResourceNetworkSecurityGatewaySecurityPolicyRule(), "google_network_security_address_group_iam_binding": tpgiamresource.ResourceIamBinding(networksecurity.NetworkSecurityProjectAddressGroupIamSchema, networksecurity.NetworkSecurityProjectAddressGroupIamUpdaterProducer, networksecurity.NetworkSecurityProjectAddressGroupIdParseFunc), diff --git a/google-beta/services/networksecurity/resource_network_security_firewall_endpoint_association.go b/google-beta/services/networksecurity/resource_network_security_firewall_endpoint_association.go new file mode 100644 index 0000000000..e117f17b16 --- /dev/null +++ b/google-beta/services/networksecurity/resource_network_security_firewall_endpoint_association.go @@ -0,0 +1,546 @@ +// 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 networksecurity + +import ( + "fmt" + "log" + "reflect" + "strings" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + + "github.com/hashicorp/terraform-provider-google-beta/google-beta/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google-beta/google-beta/transport" +) + +func ResourceNetworkSecurityFirewallEndpointAssociation() *schema.Resource { + return &schema.Resource{ + Create: resourceNetworkSecurityFirewallEndpointAssociationCreate, + Read: resourceNetworkSecurityFirewallEndpointAssociationRead, + Update: resourceNetworkSecurityFirewallEndpointAssociationUpdate, + Delete: resourceNetworkSecurityFirewallEndpointAssociationDelete, + + Importer: &schema.ResourceImporter{ + State: resourceNetworkSecurityFirewallEndpointAssociationImport, + }, + + 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, + ), + + Schema: map[string]*schema.Schema{ + "firewall_endpoint": { + Type: schema.TypeString, + Required: true, + Description: `The URL of the firewall endpoint that is being associated.`, + }, + "location": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `The location (zone) of the firewall endpoint association.`, + }, + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `The name of the firewall endpoint association resource.`, + }, + "network": { + Type: schema.TypeString, + Required: true, + Description: `The URL of the network that is being associated.`, + }, + "labels": { + Type: schema.TypeMap, + Optional: true, + Description: `A map of key/value label pairs to assign to the resource. + + +**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}, + }, + "parent": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Description: `The name of the parent this firewall endpoint association belongs to. +Format: projects/{project_id}.`, + }, + "tls_inspection_policy": { + Type: schema.TypeString, + Optional: true, + Description: `The URL of the TlsInspectionPolicy that is being associated.`, + }, + "create_time": { + Type: schema.TypeString, + Computed: true, + Description: `Time the firewall endpoint was created in UTC.`, + }, + "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}, + }, + "reconciling": { + Type: schema.TypeBool, + Computed: true, + Description: `Whether reconciling is in progress, recommended per https://google.aip.dev/128.`, + }, + "self_link": { + Type: schema.TypeString, + Computed: true, + Description: `Server-defined URL of this resource.`, + }, + "state": { + Type: schema.TypeString, + Computed: true, + Description: `The current state of the endpoint.`, + }, + "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: `Time the firewall endpoint was updated in UTC.`, + }, + }, + UseJSONNumber: true, + } +} + +func resourceNetworkSecurityFirewallEndpointAssociationCreate(d *schema.ResourceData, meta interface{}) error { + var project string + config := meta.(*transport_tpg.Config) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + if err != nil { + return err + } + + obj := make(map[string]interface{}) + firewallEndpointProp, err := expandNetworkSecurityFirewallEndpointAssociationFirewallEndpoint(d.Get("firewall_endpoint"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("firewall_endpoint"); !tpgresource.IsEmptyValue(reflect.ValueOf(firewallEndpointProp)) && (ok || !reflect.DeepEqual(v, firewallEndpointProp)) { + obj["firewallEndpoint"] = firewallEndpointProp + } + networkProp, err := expandNetworkSecurityFirewallEndpointAssociationNetwork(d.Get("network"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("network"); !tpgresource.IsEmptyValue(reflect.ValueOf(networkProp)) && (ok || !reflect.DeepEqual(v, networkProp)) { + obj["network"] = networkProp + } + tlsInspectionPolicyProp, err := expandNetworkSecurityFirewallEndpointAssociationTlsInspectionPolicy(d.Get("tls_inspection_policy"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("tls_inspection_policy"); !tpgresource.IsEmptyValue(reflect.ValueOf(tlsInspectionPolicyProp)) && (ok || !reflect.DeepEqual(v, tlsInspectionPolicyProp)) { + obj["tlsInspectionPolicy"] = tlsInspectionPolicyProp + } + labelsProp, err := expandNetworkSecurityFirewallEndpointAssociationEffectiveLabels(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, "{{NetworkSecurityBasePath}}{{parent}}/locations/{{location}}/firewallEndpointAssociations?firewallEndpointId={{name}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Creating new FirewallEndpointAssociation: %#v", obj) + billingProject := "" + + // err == nil indicates that the billing_project value was found + if bp, err := tpgresource.GetBillingProject(d, config); err == nil { + billingProject = bp + } + + 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), + }) + if err != nil { + return fmt.Errorf("Error creating FirewallEndpointAssociation: %s", err) + } + + // Store the ID now + id, err := tpgresource.ReplaceVars(d, config, "{{parent}}/locations/{{location}}/firewallEndpointAssociations/{{name}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + err = NetworkSecurityOperationWaitTime( + config, res, project, "Creating FirewallEndpointAssociation", userAgent, + d.Timeout(schema.TimeoutCreate)) + + if err != nil { + // The resource didn't actually create + d.SetId("") + return fmt.Errorf("Error waiting to create FirewallEndpointAssociation: %s", err) + } + + log.Printf("[DEBUG] Finished creating FirewallEndpointAssociation %q: %#v", d.Id(), res) + + return resourceNetworkSecurityFirewallEndpointAssociationRead(d, meta) +} + +func resourceNetworkSecurityFirewallEndpointAssociationRead(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, "{{NetworkSecurityBasePath}}{{parent}}/locations/{{location}}/firewallEndpointAssociations/{{name}}") + if err != nil { + return err + } + + billingProject := "" + + // err == nil indicates that the billing_project value was found + if bp, err := tpgresource.GetBillingProject(d, config); err == nil { + billingProject = bp + } + + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: billingProject, + RawURL: url, + UserAgent: userAgent, + }) + if err != nil { + return transport_tpg.HandleNotFoundError(err, d, fmt.Sprintf("NetworkSecurityFirewallEndpointAssociation %q", d.Id())) + } + + if err := d.Set("firewall_endpoint", flattenNetworkSecurityFirewallEndpointAssociationFirewallEndpoint(res["firewallEndpoint"], d, config)); err != nil { + return fmt.Errorf("Error reading FirewallEndpointAssociation: %s", err) + } + if err := d.Set("network", flattenNetworkSecurityFirewallEndpointAssociationNetwork(res["network"], d, config)); err != nil { + return fmt.Errorf("Error reading FirewallEndpointAssociation: %s", err) + } + if err := d.Set("tls_inspection_policy", flattenNetworkSecurityFirewallEndpointAssociationTlsInspectionPolicy(res["tlsInspectionPolicy"], d, config)); err != nil { + return fmt.Errorf("Error reading FirewallEndpointAssociation: %s", err) + } + if err := d.Set("labels", flattenNetworkSecurityFirewallEndpointAssociationLabels(res["labels"], d, config)); err != nil { + return fmt.Errorf("Error reading FirewallEndpointAssociation: %s", err) + } + if err := d.Set("self_link", flattenNetworkSecurityFirewallEndpointAssociationSelfLink(res["selfLink"], d, config)); err != nil { + return fmt.Errorf("Error reading FirewallEndpointAssociation: %s", err) + } + if err := d.Set("create_time", flattenNetworkSecurityFirewallEndpointAssociationCreateTime(res["createTime"], d, config)); err != nil { + return fmt.Errorf("Error reading FirewallEndpointAssociation: %s", err) + } + if err := d.Set("update_time", flattenNetworkSecurityFirewallEndpointAssociationUpdateTime(res["updateTime"], d, config)); err != nil { + return fmt.Errorf("Error reading FirewallEndpointAssociation: %s", err) + } + if err := d.Set("reconciling", flattenNetworkSecurityFirewallEndpointAssociationReconciling(res["reconciling"], d, config)); err != nil { + return fmt.Errorf("Error reading FirewallEndpointAssociation: %s", err) + } + if err := d.Set("state", flattenNetworkSecurityFirewallEndpointAssociationState(res["state"], d, config)); err != nil { + return fmt.Errorf("Error reading FirewallEndpointAssociation: %s", err) + } + if err := d.Set("terraform_labels", flattenNetworkSecurityFirewallEndpointAssociationTerraformLabels(res["labels"], d, config)); err != nil { + return fmt.Errorf("Error reading FirewallEndpointAssociation: %s", err) + } + if err := d.Set("effective_labels", flattenNetworkSecurityFirewallEndpointAssociationEffectiveLabels(res["labels"], d, config)); err != nil { + return fmt.Errorf("Error reading FirewallEndpointAssociation: %s", err) + } + + return nil +} + +func resourceNetworkSecurityFirewallEndpointAssociationUpdate(d *schema.ResourceData, meta interface{}) error { + var project string + config := meta.(*transport_tpg.Config) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + if err != nil { + return err + } + + billingProject := "" + + obj := make(map[string]interface{}) + firewallEndpointProp, err := expandNetworkSecurityFirewallEndpointAssociationFirewallEndpoint(d.Get("firewall_endpoint"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("firewall_endpoint"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, firewallEndpointProp)) { + obj["firewallEndpoint"] = firewallEndpointProp + } + networkProp, err := expandNetworkSecurityFirewallEndpointAssociationNetwork(d.Get("network"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("network"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, networkProp)) { + obj["network"] = networkProp + } + tlsInspectionPolicyProp, err := expandNetworkSecurityFirewallEndpointAssociationTlsInspectionPolicy(d.Get("tls_inspection_policy"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("tls_inspection_policy"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, tlsInspectionPolicyProp)) { + obj["tlsInspectionPolicy"] = tlsInspectionPolicyProp + } + labelsProp, err := expandNetworkSecurityFirewallEndpointAssociationEffectiveLabels(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, "{{NetworkSecurityBasePath}}{{parent}}/locations/{{location}}/firewallEndpointAssociations/{{name}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Updating FirewallEndpointAssociation %q: %#v", d.Id(), obj) + updateMask := []string{} + + if d.HasChange("firewall_endpoint") { + updateMask = append(updateMask, "firewallEndpoint") + } + + if d.HasChange("network") { + updateMask = append(updateMask, "network") + } + + if d.HasChange("tls_inspection_policy") { + updateMask = append(updateMask, "tlsInspectionPolicy") + } + + 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), + }) + + if err != nil { + return fmt.Errorf("Error updating FirewallEndpointAssociation %q: %s", d.Id(), err) + } else { + log.Printf("[DEBUG] Finished updating FirewallEndpointAssociation %q: %#v", d.Id(), res) + } + + err = NetworkSecurityOperationWaitTime( + config, res, project, "Updating FirewallEndpointAssociation", userAgent, + d.Timeout(schema.TimeoutUpdate)) + + if err != nil { + return err + } + } + + return resourceNetworkSecurityFirewallEndpointAssociationRead(d, meta) +} + +func resourceNetworkSecurityFirewallEndpointAssociationDelete(d *schema.ResourceData, meta interface{}) error { + var project string + config := meta.(*transport_tpg.Config) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + if err != nil { + return err + } + + billingProject := "" + + url, err := tpgresource.ReplaceVars(d, config, "{{NetworkSecurityBasePath}}{{parent}}/locations/{{location}}/firewallEndpointAssociations/{{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 + } + + log.Printf("[DEBUG] Deleting FirewallEndpointAssociation %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), + }) + if err != nil { + return transport_tpg.HandleNotFoundError(err, d, "FirewallEndpointAssociation") + } + + err = NetworkSecurityOperationWaitTime( + config, res, project, "Deleting FirewallEndpointAssociation", userAgent, + d.Timeout(schema.TimeoutDelete)) + + if err != nil { + return err + } + + log.Printf("[DEBUG] Finished deleting FirewallEndpointAssociation %q: %#v", d.Id(), res) + return nil +} + +func resourceNetworkSecurityFirewallEndpointAssociationImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + config := meta.(*transport_tpg.Config) + if err := tpgresource.ParseImportId([]string{ + "^(?P.+)/locations/(?P[^/]+)/firewallEndpointAssociations/(?P[^/]+)$", + }, d, config); err != nil { + return nil, err + } + + // Replace import id for the resource id + id, err := tpgresource.ReplaceVars(d, config, "{{parent}}/locations/{{location}}/firewallEndpointAssociations/{{name}}") + if err != nil { + return nil, fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + return []*schema.ResourceData{d}, nil +} + +func flattenNetworkSecurityFirewallEndpointAssociationFirewallEndpoint(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkSecurityFirewallEndpointAssociationNetwork(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkSecurityFirewallEndpointAssociationTlsInspectionPolicy(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkSecurityFirewallEndpointAssociationLabels(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 flattenNetworkSecurityFirewallEndpointAssociationSelfLink(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkSecurityFirewallEndpointAssociationCreateTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkSecurityFirewallEndpointAssociationUpdateTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkSecurityFirewallEndpointAssociationReconciling(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkSecurityFirewallEndpointAssociationState(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkSecurityFirewallEndpointAssociationTerraformLabels(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 flattenNetworkSecurityFirewallEndpointAssociationEffectiveLabels(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func expandNetworkSecurityFirewallEndpointAssociationFirewallEndpoint(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandNetworkSecurityFirewallEndpointAssociationNetwork(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandNetworkSecurityFirewallEndpointAssociationTlsInspectionPolicy(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandNetworkSecurityFirewallEndpointAssociationEffectiveLabels(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-beta/services/networksecurity/resource_network_security_firewall_endpoint_association_sweeper.go b/google-beta/services/networksecurity/resource_network_security_firewall_endpoint_association_sweeper.go new file mode 100644 index 0000000000..e18719a7f5 --- /dev/null +++ b/google-beta/services/networksecurity/resource_network_security_firewall_endpoint_association_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 networksecurity + +import ( + "context" + "log" + "strings" + "testing" + + "github.com/hashicorp/terraform-provider-google-beta/google-beta/envvar" + "github.com/hashicorp/terraform-provider-google-beta/google-beta/sweeper" + "github.com/hashicorp/terraform-provider-google-beta/google-beta/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google-beta/google-beta/transport" +) + +func init() { + sweeper.AddTestSweepers("NetworkSecurityFirewallEndpointAssociation", testSweepNetworkSecurityFirewallEndpointAssociation) +} + +// At the time of writing, the CI only passes us-central1 as the region +func testSweepNetworkSecurityFirewallEndpointAssociation(region string) error { + resourceName := "NetworkSecurityFirewallEndpointAssociation" + 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://networksecurity.googleapis.com/v1beta1/{{parent}}/locations/{{location}}/firewallEndpointAssociations", "?")[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["firewallEndpointAssociations"] + 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://networksecurity.googleapis.com/v1beta1/{{parent}}/locations/{{location}}/firewallEndpointAssociations/{{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-beta/services/networksecurity/resource_network_security_firewall_endpoint_association_test.go b/google-beta/services/networksecurity/resource_network_security_firewall_endpoint_association_test.go new file mode 100644 index 0000000000..0fe26d22a8 --- /dev/null +++ b/google-beta/services/networksecurity/resource_network_security_firewall_endpoint_association_test.go @@ -0,0 +1,152 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 +package networksecurity_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-beta/google-beta/acctest" + "github.com/hashicorp/terraform-provider-google-beta/google-beta/envvar" + "github.com/hashicorp/terraform-provider-google-beta/google-beta/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google-beta/google-beta/transport" +) + +func TestAccNetworkSecurityFirewallEndpointAssociations_basic(t *testing.T) { + acctest.SkipIfVcr(t) + t.Parallel() + + orgId := envvar.GetTestOrgFromEnv(t) + randomSuffix := acctest.RandString(t, 10) + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderBetaFactories(t), + CheckDestroy: testAccCheckNetworkSecurityFirewallEndpointDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccNetworkSecurityFirewallEndpointAssociation_basic(randomSuffix, orgId), + }, + { + ResourceName: "google_network_security_firewall_endpoint_association.foobar", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"labels", "terraform_labels"}, + }, + { + Config: testAccNetworkSecurityFirewallEndpointAssociation_update(randomSuffix, orgId), + }, + { + ResourceName: "google_network_security_firewall_endpoint_association.foobar", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"labels", "terraform_labels"}, + }, + }, + }) +} + +func testAccNetworkSecurityFirewallEndpointAssociation_basic(randomSuffix string, orgId string) string { + return fmt.Sprintf(` +resource "google_compute_network" "foobar" { + provider = google-beta + name = "tf-test-my-vpc%s" + auto_create_subnetworks = false +} + +resource "google_network_security_firewall_endpoint" "foobar" { + provider = google-beta + name = "tf-test-my-firewall-endpoint%s" + parent = "organizations/%s" + location = "us-central1-a" +} + +# TODO: add tlsInspectionPolicy once resource is ready +resource "google_network_security_firewall_endpoint_association" "foobar" { + provider = google-beta + name = "tf-test-my-firewall-endpoint%s" + parent = "organizations/%s" + location = "us-central1-a" + firewall_endpoint = google_network_security_firewall_endpoint.foobar.id + network = google_compute_network.foobar.id + + labels = { + foo = "bar" + } +} +`, randomSuffix, randomSuffix, orgId, randomSuffix, orgId) +} + +func testAccNetworkSecurityFirewallEndpointAssociation_update(randomSuffix string, orgId string) string { + return fmt.Sprintf(` +resource "google_compute_network" "foobar" { + provider = google-beta + name = "tf-test-my-vpc%s" + auto_create_subnetworks = false +} + +resource "google_network_security_firewall_endpoint" "foobar" { + provider = google-beta + name = "tf-test-my-firewall-endpoint%s" + parent = "organizations/%s" + location = "us-central1-a" +} + +# TODO: add tlsInspectionPolicy once resource is ready +resource "google_network_security_firewall_endpoint_association" "foobar" { + provider = google-beta + name = "tf-test-my-firewall-endpoint%s" + parent = "organizations/%s" + location = "us-central1-a" + firewall_endpoint = google_network_security_firewall_endpoint.foobar.id + network = google_compute_network.foobar.id + + labels = { + foo = "bar-updated" + } +} +`, randomSuffix, randomSuffix, orgId, randomSuffix, orgId) +} + +func testAccCheckNetworkSecurityFirewallEndpointAssociationDestroyProducer(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_security_firewall_endpoint_association" { + continue + } + if strings.HasPrefix(name, "data.") { + continue + } + + config := acctest.GoogleProviderConfig(t) + + url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{NetworkSecurityBasePath}}{{parent}}/locations/{{location}}/firewallEndpointAssociations/{{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("NetworkSecurityFirewallEndpointAssociation still exists at %s", url) + } + } + + return nil + } +} diff --git a/website/docs/r/network_security_firewall_endpoint_association.html.markdown b/website/docs/r/network_security_firewall_endpoint_association.html.markdown new file mode 100644 index 0000000000..40e057c740 --- /dev/null +++ b/website/docs/r/network_security_firewall_endpoint_association.html.markdown @@ -0,0 +1,166 @@ +--- +# ---------------------------------------------------------------------------- +# +# *** 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: "Network security" +description: |- + Firewall endpoint association links a firewall endpoint to a VPC network in + the same zone. +--- + +# google\_network\_security\_firewall\_endpoint\_association + +Firewall endpoint association links a firewall endpoint to a VPC network in +the same zone. After you define this association, Cloud Firewall forwards the +zonal workload traffic in your VPC network that requires layer 7 inspection to +the attached firewall endpoint. + +~> **Warning:** This resource is in beta, and should be used with the terraform-provider-google-beta provider. +See [Provider Versions](https://terraform.io/docs/providers/google/guides/provider_versions.html) for more details on beta resources. + +To get more information about FirewallEndpointAssociation, see: + +* [API documentation](https://cloud.google.com/firewall/docs/reference/network-security/rest/v1beta1/projects.locations.firewallEndpointAssociations#FirewallEndpointAssociation) +* How-to Guides + * [Firewall endpoint overview](https://cloud.google.com/firewall/docs/about-firewall-endpoints) + * [Create and associate firewall endpoints](https://cloud.google.com/firewall/docs/configure-firewall-endpoints) + +## Example Usage - Network Security Firewall Endpoint Association Basic + + +```hcl +resource "google_network_security_firewall_endpoint" "default" { + provider = google-beta + name = "my-firewall-endpoint" + parent = "organizations/123456789" + location = "us-central1-a" + + labels = { + foo = "bar" + } +} + +resource "google_network_security_firewall_endpoint_association" "default_association" { + provider = google-beta + name = "my-firewall-endpoint-association" + parent = "projects/my-project-name" + location = "us-central1-a" + + labels = { + foo = "bar" + } +} +``` + +## Argument Reference + +The following arguments are supported: + + +* `firewall_endpoint` - + (Required) + The URL of the firewall endpoint that is being associated. + +* `network` - + (Required) + The URL of the network that is being associated. + +* `name` - + (Required) + The name of the firewall endpoint association resource. + +* `location` - + (Required) + The location (zone) of the firewall endpoint association. + + +- - - + + +* `tls_inspection_policy` - + (Optional) + The URL of the TlsInspectionPolicy that is being associated. + +* `labels` - + (Optional) + A map of key/value label pairs to assign to the resource. + + **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. + +* `parent` - + (Optional) + The name of the parent this firewall endpoint association belongs to. + Format: projects/{project_id}. + + +## Attributes Reference + +In addition to the arguments listed above, the following computed attributes are exported: + +* `id` - an identifier for the resource with format `{{parent}}/locations/{{location}}/firewallEndpointAssociations/{{name}}` + +* `self_link` - + Server-defined URL of this resource. + +* `create_time` - + Time the firewall endpoint was created in UTC. + +* `update_time` - + Time the firewall endpoint was updated in UTC. + +* `reconciling` - + Whether reconciling is in progress, recommended per https://google.aip.dev/128. + +* `state` - + The current state of the endpoint. + +* `terraform_labels` - + The combination of labels configured directly on the resource + and default labels configured on the provider. + +* `effective_labels` - + All of labels (key/value pairs) present on the resource in GCP, including the labels configured through Terraform, other clients and services. + + +## 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 + + +FirewallEndpointAssociation can be imported using any of these accepted formats: + +* `{{parent}}/locations/{{location}}/firewallEndpointAssociations/{{name}}` + + +In Terraform v1.5.0 and later, use an [`import` block](https://developer.hashicorp.com/terraform/language/import) to import FirewallEndpointAssociation using one of the formats above. For example: + +```tf +import { + id = "{{parent}}/locations/{{location}}/firewallEndpointAssociations/{{name}}" + to = google_network_security_firewall_endpoint_association.default +} +``` + +When using the [`terraform import` command](https://developer.hashicorp.com/terraform/cli/commands/import), FirewallEndpointAssociation can be imported using one of the formats above. For example: + +``` +$ terraform import google_network_security_firewall_endpoint_association.default {{parent}}/locations/{{location}}/firewallEndpointAssociations/{{name}} +```