From ce306d728d846053abe0884534e16fbc2509086e Mon Sep 17 00:00:00 2001 From: Modular Magician Date: Wed, 23 Oct 2024 00:34:08 +0000 Subject: [PATCH] Migrate Network Firewall Policy Association (global and region) resource from DCL to MMv1 (#11366) Co-authored-by: Cameron Thornton [upstream:9a1402bf3fa39860cad1fb258010cbf01450e8d8] Signed-off-by: Modular Magician --- .changelog/11366.txt | 6 + .../provider/provider_dcl_resources.go | 50 ++-- .../provider/provider_mmv1_resources.go | 6 +- ...ute_network_firewall_policy_association.go | 261 +++++++++------- ...ewall_policy_association_generated_test.go | 111 +++---- ...ork_firewall_policy_association_sweeper.go | 139 +++++++++ ...mpute_network_firewall_policy_rule_test.go | 25 ++ ...ion_network_firewall_policy_association.go | 278 ++++++++++-------- ...ewall_policy_association_generated_test.go | 116 +++----- ...ork_firewall_policy_association_sweeper.go | 139 +++++++++ ..._firewall_policy_association.html.markdown | 69 +++-- ..._firewall_policy_association.html.markdown | 83 +++--- 12 files changed, 823 insertions(+), 460 deletions(-) create mode 100644 .changelog/11366.txt create mode 100644 google-beta/services/compute/resource_compute_network_firewall_policy_association_sweeper.go create mode 100644 google-beta/services/compute/resource_compute_region_network_firewall_policy_association_sweeper.go diff --git a/.changelog/11366.txt b/.changelog/11366.txt new file mode 100644 index 0000000000..832fef3d5f --- /dev/null +++ b/.changelog/11366.txt @@ -0,0 +1,6 @@ +```release-note:enhancement +compute: `google_compute_network_firewall_policy_association` now uses MMv1 engine instead of DCL. +``` +```release-note:enhancement +compute: `google_compute_region_network_firewall_policy_association` now uses MMv1 engine instead of DCL. +``` \ No newline at end of file diff --git a/google-beta/provider/provider_dcl_resources.go b/google-beta/provider/provider_dcl_resources.go index d15cf5826c..a406a238f9 100644 --- a/google-beta/provider/provider_dcl_resources.go +++ b/google-beta/provider/provider_dcl_resources.go @@ -36,30 +36,28 @@ import ( ) var dclResources = map[string]*schema.Resource{ - "google_apikeys_key": apikeys.ResourceApikeysKey(), - "google_assured_workloads_workload": assuredworkloads.ResourceAssuredWorkloadsWorkload(), - "google_cloudbuild_worker_pool": cloudbuild.ResourceCloudbuildWorkerPool(), - "google_clouddeploy_delivery_pipeline": clouddeploy.ResourceClouddeployDeliveryPipeline(), - "google_clouddeploy_target": clouddeploy.ResourceClouddeployTarget(), - "google_compute_firewall_policy": compute.ResourceComputeFirewallPolicy(), - "google_compute_firewall_policy_association": compute.ResourceComputeFirewallPolicyAssociation(), - "google_compute_firewall_policy_rule": compute.ResourceComputeFirewallPolicyRule(), - "google_compute_network_firewall_policy_association": compute.ResourceComputeNetworkFirewallPolicyAssociation(), - "google_compute_region_network_firewall_policy_association": compute.ResourceComputeRegionNetworkFirewallPolicyAssociation(), - "google_container_aws_cluster": containeraws.ResourceContainerAwsCluster(), - "google_container_aws_node_pool": containeraws.ResourceContainerAwsNodePool(), - "google_container_azure_client": containerazure.ResourceContainerAzureClient(), - "google_container_azure_cluster": containerazure.ResourceContainerAzureCluster(), - "google_container_azure_node_pool": containerazure.ResourceContainerAzureNodePool(), - "google_dataplex_asset": dataplex.ResourceDataplexAsset(), - "google_dataplex_lake": dataplex.ResourceDataplexLake(), - "google_dataplex_zone": dataplex.ResourceDataplexZone(), - "google_dataproc_workflow_template": dataproc.ResourceDataprocWorkflowTemplate(), - "google_eventarc_channel": eventarc.ResourceEventarcChannel(), - "google_eventarc_google_channel_config": eventarc.ResourceEventarcGoogleChannelConfig(), - "google_eventarc_trigger": eventarc.ResourceEventarcTrigger(), - "google_firebaserules_release": firebaserules.ResourceFirebaserulesRelease(), - "google_firebaserules_ruleset": firebaserules.ResourceFirebaserulesRuleset(), - "google_gke_hub_feature_membership": gkehub.ResourceGkeHubFeatureMembership(), - "google_recaptcha_enterprise_key": recaptchaenterprise.ResourceRecaptchaEnterpriseKey(), + "google_apikeys_key": apikeys.ResourceApikeysKey(), + "google_assured_workloads_workload": assuredworkloads.ResourceAssuredWorkloadsWorkload(), + "google_cloudbuild_worker_pool": cloudbuild.ResourceCloudbuildWorkerPool(), + "google_clouddeploy_delivery_pipeline": clouddeploy.ResourceClouddeployDeliveryPipeline(), + "google_clouddeploy_target": clouddeploy.ResourceClouddeployTarget(), + "google_compute_firewall_policy": compute.ResourceComputeFirewallPolicy(), + "google_compute_firewall_policy_association": compute.ResourceComputeFirewallPolicyAssociation(), + "google_compute_firewall_policy_rule": compute.ResourceComputeFirewallPolicyRule(), + "google_container_aws_cluster": containeraws.ResourceContainerAwsCluster(), + "google_container_aws_node_pool": containeraws.ResourceContainerAwsNodePool(), + "google_container_azure_client": containerazure.ResourceContainerAzureClient(), + "google_container_azure_cluster": containerazure.ResourceContainerAzureCluster(), + "google_container_azure_node_pool": containerazure.ResourceContainerAzureNodePool(), + "google_dataplex_asset": dataplex.ResourceDataplexAsset(), + "google_dataplex_lake": dataplex.ResourceDataplexLake(), + "google_dataplex_zone": dataplex.ResourceDataplexZone(), + "google_dataproc_workflow_template": dataproc.ResourceDataprocWorkflowTemplate(), + "google_eventarc_channel": eventarc.ResourceEventarcChannel(), + "google_eventarc_google_channel_config": eventarc.ResourceEventarcGoogleChannelConfig(), + "google_eventarc_trigger": eventarc.ResourceEventarcTrigger(), + "google_firebaserules_release": firebaserules.ResourceFirebaserulesRelease(), + "google_firebaserules_ruleset": firebaserules.ResourceFirebaserulesRuleset(), + "google_gke_hub_feature_membership": gkehub.ResourceGkeHubFeatureMembership(), + "google_recaptcha_enterprise_key": recaptchaenterprise.ResourceRecaptchaEnterpriseKey(), } diff --git a/google-beta/provider/provider_mmv1_resources.go b/google-beta/provider/provider_mmv1_resources.go index f3214233b8..03c4caf266 100644 --- a/google-beta/provider/provider_mmv1_resources.go +++ b/google-beta/provider/provider_mmv1_resources.go @@ -496,9 +496,9 @@ var handwrittenIAMDatasources = map[string]*schema.Resource{ } // Resources -// Generated resources: 542 +// Generated resources: 544 // Generated IAM resources: 291 -// Total generated resources: 833 +// Total generated resources: 835 var generatedResources = map[string]*schema.Resource{ "google_folder_access_approval_settings": accessapproval.ResourceAccessApprovalFolderSettings(), "google_organization_access_approval_settings": accessapproval.ResourceAccessApprovalOrganizationSettings(), @@ -733,6 +733,7 @@ var generatedResources = map[string]*schema.Resource{ "google_compute_network_endpoint_group": compute.ResourceComputeNetworkEndpointGroup(), "google_compute_network_endpoints": compute.ResourceComputeNetworkEndpoints(), "google_compute_network_firewall_policy": compute.ResourceComputeNetworkFirewallPolicy(), + "google_compute_network_firewall_policy_association": compute.ResourceComputeNetworkFirewallPolicyAssociation(), "google_compute_network_firewall_policy_rule": compute.ResourceComputeNetworkFirewallPolicyRule(), "google_compute_network_firewall_policy_with_rules": compute.ResourceComputeNetworkFirewallPolicyWithRules(), "google_compute_network_peering_routes_config": compute.ResourceComputeNetworkPeeringRoutesConfig(), @@ -761,6 +762,7 @@ var generatedResources = map[string]*schema.Resource{ "google_compute_region_network_endpoint": compute.ResourceComputeRegionNetworkEndpoint(), "google_compute_region_network_endpoint_group": compute.ResourceComputeRegionNetworkEndpointGroup(), "google_compute_region_network_firewall_policy": compute.ResourceComputeRegionNetworkFirewallPolicy(), + "google_compute_region_network_firewall_policy_association": compute.ResourceComputeRegionNetworkFirewallPolicyAssociation(), "google_compute_region_network_firewall_policy_rule": compute.ResourceComputeRegionNetworkFirewallPolicyRule(), "google_compute_region_network_firewall_policy_with_rules": compute.ResourceComputeRegionNetworkFirewallPolicyWithRules(), "google_compute_region_per_instance_config": compute.ResourceComputeRegionPerInstanceConfig(), diff --git a/google-beta/services/compute/resource_compute_network_firewall_policy_association.go b/google-beta/services/compute/resource_compute_network_firewall_policy_association.go index f3581e306d..f2cfb5211a 100644 --- a/google-beta/services/compute/resource_compute_network_firewall_policy_association.go +++ b/google-beta/services/compute/resource_compute_network_firewall_policy_association.go @@ -3,34 +3,31 @@ // ---------------------------------------------------------------------------- // -// *** AUTO GENERATED CODE *** Type: DCL *** +// *** AUTO GENERATED CODE *** Type: MMv1 *** // // ---------------------------------------------------------------------------- // -// This file is managed by Magic Modules (https://github.com/GoogleCloudPlatform/magic-modules) -// and is based on the DCL (https://github.com/GoogleCloudPlatform/declarative-resource-client-library). -// Changes will need to be made to the DCL or Magic Modules instead of here. +// This file is automatically generated by Magic Modules and manual +// changes will be clobbered when the file is regenerated. // -// We are not currently able to accept contributions to this file. If changes -// are required, please file an issue at https://github.com/hashicorp/terraform-provider-google/issues/new/choose +// Please read more about how to change this file in +// .github/CONTRIBUTING.md. // // ---------------------------------------------------------------------------- package compute import ( - "context" "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" - dcl "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" - compute "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/compute/beta" - - "github.com/hashicorp/terraform-provider-google-beta/google-beta/tpgdclresource" "github.com/hashicorp/terraform-provider-google-beta/google-beta/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google-beta/google-beta/transport" ) @@ -49,9 +46,9 @@ func ResourceComputeNetworkFirewallPolicyAssociation() *schema.Resource { Create: schema.DefaultTimeout(20 * time.Minute), Delete: schema.DefaultTimeout(20 * time.Minute), }, + CustomizeDiff: customdiff.All( tpgresource.DefaultProviderProject, - tpgresource.DefaultProviderRegion, ), Schema: map[string]*schema.Schema{ @@ -60,86 +57,107 @@ func ResourceComputeNetworkFirewallPolicyAssociation() *schema.Resource { Required: true, ForceNew: true, DiffSuppressFunc: tpgresource.CompareSelfLinkOrResourceName, - Description: "The target that the firewall policy is attached to.", + Description: `The target that the firewall policy is attached to.`, }, - "firewall_policy": { Type: schema.TypeString, Required: true, ForceNew: true, DiffSuppressFunc: tpgresource.CompareSelfLinkOrResourceName, - Description: "The firewall policy ID of the association.", + Description: `The firewall policy of the resource.`, }, - "name": { Type: schema.TypeString, Required: true, ForceNew: true, - Description: "The name for an association.", + Description: `The name for an association.`, }, - - "project": { - Type: schema.TypeString, - Computed: true, - Optional: true, - ForceNew: true, - DiffSuppressFunc: tpgresource.CompareSelfLinkOrResourceName, - Description: "The project for the resource", - }, - "short_name": { Type: schema.TypeString, Computed: true, - Description: "The short name of the firewall policy of the association.", + Description: `The short name of the firewall policy of the association.`, + }, + "project": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, }, }, + UseJSONNumber: true, } } func resourceComputeNetworkFirewallPolicyAssociationCreate(d *schema.ResourceData, meta interface{}) error { config := meta.(*transport_tpg.Config) - project, err := tpgresource.GetProject(d, config) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { return err } - obj := &compute.NetworkFirewallPolicyAssociation{ - AttachmentTarget: dcl.String(d.Get("attachment_target").(string)), - FirewallPolicy: dcl.String(d.Get("firewall_policy").(string)), - Name: dcl.String(d.Get("name").(string)), - Project: dcl.String(project), + obj := make(map[string]interface{}) + nameProp, err := expandComputeNetworkFirewallPolicyAssociationName(d.Get("name"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("name"); !tpgresource.IsEmptyValue(reflect.ValueOf(nameProp)) && (ok || !reflect.DeepEqual(v, nameProp)) { + obj["name"] = nameProp } - - id, err := tpgresource.ReplaceVarsForId(d, config, "projects/{{project}}/global/firewallPolicies/{{firewall_policy}}/associations/{{name}}") + attachmentTargetProp, err := expandComputeNetworkFirewallPolicyAssociationAttachmentTarget(d.Get("attachment_target"), d, config) if err != nil { - return fmt.Errorf("error constructing id: %s", err) + return err + } else if v, ok := d.GetOkExists("attachment_target"); !tpgresource.IsEmptyValue(reflect.ValueOf(attachmentTargetProp)) && (ok || !reflect.DeepEqual(v, attachmentTargetProp)) { + obj["attachmentTarget"] = attachmentTargetProp } - d.SetId(id) - directive := tpgdclresource.CreateDirective - userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + + url, err := tpgresource.ReplaceVarsForId(d, config, "{{ComputeBasePath}}projects/{{project}}/global/firewallPolicies/{{firewall_policy}}/addAssociation") if err != nil { return err } - billingProject := project + + log.Printf("[DEBUG] Creating new NetworkFirewallPolicyAssociation: %#v", obj) + billingProject := "" + + project, err := tpgresource.GetProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for NetworkFirewallPolicyAssociation: %s", err) + } + billingProject = strings.TrimPrefix(project, "projects/") + // err == nil indicates that the billing_project value was found if bp, err := tpgresource.GetBillingProject(d, config); err == nil { billingProject = bp } - client := transport_tpg.NewDCLComputeClient(config, userAgent, billingProject, d.Timeout(schema.TimeoutCreate)) - if bp, err := tpgresource.ReplaceVars(d, config, client.Config.BasePath); err != nil { - d.SetId("") - return fmt.Errorf("Could not format %q: %w", client.Config.BasePath, err) - } else { - client.Config.BasePath = 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 NetworkFirewallPolicyAssociation: %s", err) + } + + // Store the ID now + id, err := tpgresource.ReplaceVarsForId(d, config, "projects/{{project}}/global/firewallPolicies/{{firewall_policy}}/associations/{{name}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) } - res, err := client.ApplyNetworkFirewallPolicyAssociation(context.Background(), obj, directive...) + d.SetId(id) + + err = ComputeOperationWaitTime( + config, res, tpgresource.GetResourceNameFromSelfLink(project), "Creating NetworkFirewallPolicyAssociation", userAgent, + d.Timeout(schema.TimeoutCreate)) - if _, ok := err.(dcl.DiffAfterApplyError); ok { - log.Printf("[DEBUG] Diff after apply returned from the DCL: %s", err) - } else if err != nil { + if err != nil { // The resource didn't actually create d.SetId("") - return fmt.Errorf("Error creating NetworkFirewallPolicyAssociation: %s", err) + return fmt.Errorf("Error waiting to create NetworkFirewallPolicyAssociation: %s", err) } log.Printf("[DEBUG] Finished creating NetworkFirewallPolicyAssociation %q: %#v", d.Id(), res) @@ -149,54 +167,54 @@ func resourceComputeNetworkFirewallPolicyAssociationCreate(d *schema.ResourceDat func resourceComputeNetworkFirewallPolicyAssociationRead(d *schema.ResourceData, meta interface{}) error { config := meta.(*transport_tpg.Config) - project, err := tpgresource.GetProject(d, config) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { return err } - obj := &compute.NetworkFirewallPolicyAssociation{ - AttachmentTarget: dcl.String(d.Get("attachment_target").(string)), - FirewallPolicy: dcl.String(d.Get("firewall_policy").(string)), - Name: dcl.String(d.Get("name").(string)), - Project: dcl.String(project), + url, err := tpgresource.ReplaceVarsForId(d, config, "{{ComputeBasePath}}projects/{{project}}/global/firewallPolicies/{{firewall_policy}}/getAssociation?name={{name}}") + if err != nil { + return err } - userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + billingProject := "" + + project, err := tpgresource.GetProject(d, config) if err != nil { - return err + return fmt.Errorf("Error fetching project for NetworkFirewallPolicyAssociation: %s", err) } - billingProject := project + billingProject = strings.TrimPrefix(project, "projects/") + // err == nil indicates that the billing_project value was found if bp, err := tpgresource.GetBillingProject(d, config); err == nil { billingProject = bp } - client := transport_tpg.NewDCLComputeClient(config, userAgent, billingProject, d.Timeout(schema.TimeoutRead)) - if bp, err := tpgresource.ReplaceVars(d, config, client.Config.BasePath); err != nil { - d.SetId("") - return fmt.Errorf("Could not format %q: %w", client.Config.BasePath, err) - } else { - client.Config.BasePath = bp - } - res, err := client.GetNetworkFirewallPolicyAssociation(context.Background(), obj) + + 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 { - resourceName := fmt.Sprintf("ComputeNetworkFirewallPolicyAssociation %q", d.Id()) - return tpgdclresource.HandleNotFoundDCLError(err, d, resourceName) + return transport_tpg.HandleNotFoundError(err, d, fmt.Sprintf("ComputeNetworkFirewallPolicyAssociation %q", d.Id())) } - if err = d.Set("attachment_target", res.AttachmentTarget); err != nil { - return fmt.Errorf("error setting attachment_target in state: %s", err) + if err := d.Set("project", project); err != nil { + return fmt.Errorf("Error reading NetworkFirewallPolicyAssociation: %s", err) } - if err = d.Set("firewall_policy", res.FirewallPolicy); err != nil { - return fmt.Errorf("error setting firewall_policy in state: %s", err) - } - if err = d.Set("name", res.Name); err != nil { - return fmt.Errorf("error setting name in state: %s", err) + + if err := d.Set("name", flattenComputeNetworkFirewallPolicyAssociationName(res["name"], d, config)); err != nil { + return fmt.Errorf("Error reading NetworkFirewallPolicyAssociation: %s", err) } - if err = d.Set("project", res.Project); err != nil { - return fmt.Errorf("error setting project in state: %s", err) + if err := d.Set("attachment_target", flattenComputeNetworkFirewallPolicyAssociationAttachmentTarget(res["attachmentTarget"], d, config)); err != nil { + return fmt.Errorf("Error reading NetworkFirewallPolicyAssociation: %s", err) } - if err = d.Set("short_name", res.ShortName); err != nil { - return fmt.Errorf("error setting short_name in state: %s", err) + if err := d.Set("short_name", flattenComputeNetworkFirewallPolicyAssociationShortName(res["shortName"], d, config)); err != nil { + return fmt.Errorf("Error reading NetworkFirewallPolicyAssociation: %s", err) } return nil @@ -204,49 +222,66 @@ func resourceComputeNetworkFirewallPolicyAssociationRead(d *schema.ResourceData, func resourceComputeNetworkFirewallPolicyAssociationDelete(d *schema.ResourceData, meta interface{}) error { config := meta.(*transport_tpg.Config) - project, err := tpgresource.GetProject(d, config) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { return err } - obj := &compute.NetworkFirewallPolicyAssociation{ - AttachmentTarget: dcl.String(d.Get("attachment_target").(string)), - FirewallPolicy: dcl.String(d.Get("firewall_policy").(string)), - Name: dcl.String(d.Get("name").(string)), - Project: dcl.String(project), + billingProject := "" + + project, err := tpgresource.GetProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for NetworkFirewallPolicyAssociation: %s", err) } + billingProject = strings.TrimPrefix(project, "projects/") - log.Printf("[DEBUG] Deleting NetworkFirewallPolicyAssociation %q", d.Id()) - userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + url, err := tpgresource.ReplaceVarsForId(d, config, "{{ComputeBasePath}}projects/{{project}}/global/firewallPolicies/{{firewall_policy}}/removeAssociation?name={{name}}") if err != nil { return err } - billingProject := project + + 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 } - client := transport_tpg.NewDCLComputeClient(config, userAgent, billingProject, d.Timeout(schema.TimeoutDelete)) - if bp, err := tpgresource.ReplaceVars(d, config, client.Config.BasePath); err != nil { - d.SetId("") - return fmt.Errorf("Could not format %q: %w", client.Config.BasePath, err) - } else { - client.Config.BasePath = bp + + headers := make(http.Header) + + log.Printf("[DEBUG] Deleting NetworkFirewallPolicyAssociation %q", d.Id()) + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: billingProject, + RawURL: url, + UserAgent: userAgent, + Body: obj, + Timeout: d.Timeout(schema.TimeoutDelete), + Headers: headers, + }) + if err != nil { + return transport_tpg.HandleNotFoundError(err, d, "NetworkFirewallPolicyAssociation") } - if err := client.DeleteNetworkFirewallPolicyAssociation(context.Background(), obj); err != nil { - return fmt.Errorf("Error deleting NetworkFirewallPolicyAssociation: %s", err) + + err = ComputeOperationWaitTime( + config, res, tpgresource.GetResourceNameFromSelfLink(project), "Deleting NetworkFirewallPolicyAssociation", userAgent, + d.Timeout(schema.TimeoutDelete)) + + if err != nil { + return err } - log.Printf("[DEBUG] Finished deleting NetworkFirewallPolicyAssociation %q", d.Id()) + log.Printf("[DEBUG] Finished deleting NetworkFirewallPolicyAssociation %q: %#v", d.Id(), res) return nil } func resourceComputeNetworkFirewallPolicyAssociationImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { config := meta.(*transport_tpg.Config) - if err := tpgresource.ParseImportId([]string{ - "projects/(?P[^/]+)/global/firewallPolicies/(?P[^/]+)/associations/(?P[^/]+)", - "(?P[^/]+)/(?P[^/]+)/(?P[^/]+)", + "^projects/(?P[^/]+)/global/firewallPolicies/(?P[^/]+)/associations/(?P[^/]+)$", + "^(?P[^/]+)/(?P[^/]+)/(?P[^/]+)$", + "^(?P[^/]+)/(?P[^/]+)$", }, d, config); err != nil { return nil, err } @@ -260,3 +295,23 @@ func resourceComputeNetworkFirewallPolicyAssociationImport(d *schema.ResourceDat return []*schema.ResourceData{d}, nil } + +func flattenComputeNetworkFirewallPolicyAssociationName(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenComputeNetworkFirewallPolicyAssociationAttachmentTarget(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenComputeNetworkFirewallPolicyAssociationShortName(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func expandComputeNetworkFirewallPolicyAssociationName(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandComputeNetworkFirewallPolicyAssociationAttachmentTarget(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} diff --git a/google-beta/services/compute/resource_compute_network_firewall_policy_association_generated_test.go b/google-beta/services/compute/resource_compute_network_firewall_policy_association_generated_test.go index 82dd2a252f..a533c49aa9 100644 --- a/google-beta/services/compute/resource_compute_network_firewall_policy_association_generated_test.go +++ b/google-beta/services/compute/resource_compute_network_firewall_policy_association_generated_test.go @@ -3,37 +3,35 @@ // ---------------------------------------------------------------------------- // -// *** AUTO GENERATED CODE *** Type: DCL *** +// *** AUTO GENERATED CODE *** Type: MMv1 *** // // ---------------------------------------------------------------------------- // -// This file is managed by Magic Modules (https://github.com/GoogleCloudPlatform/magic-modules) -// and is based on the DCL (https://github.com/GoogleCloudPlatform/declarative-resource-client-library). -// Changes will need to be made to the DCL or Magic Modules instead of here. +// This file is automatically generated by Magic Modules and manual +// changes will be clobbered when the file is regenerated. // -// We are not currently able to accept contributions to this file. If changes -// are required, please file an issue at https://github.com/hashicorp/terraform-provider-google/issues/new/choose +// Please read more about how to change this file in +// .github/CONTRIBUTING.md. // // ---------------------------------------------------------------------------- package compute_test import ( - "context" "fmt" - dcl "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" - compute "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/compute/beta" - "github.com/hashicorp/terraform-plugin-testing/helper/resource" - "github.com/hashicorp/terraform-plugin-testing/terraform" "strings" "testing" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" + "github.com/hashicorp/terraform-provider-google-beta/google-beta/acctest" "github.com/hashicorp/terraform-provider-google-beta/google-beta/envvar" + "github.com/hashicorp/terraform-provider-google-beta/google-beta/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google-beta/google-beta/transport" ) -func TestAccComputeNetworkFirewallPolicyAssociation_GlobalHandWritten(t *testing.T) { +func TestAccComputeNetworkFirewallPolicyAssociation_networkFirewallPolicyAssociationExample(t *testing.T) { t.Parallel() context := map[string]interface{}{ @@ -47,77 +45,44 @@ func TestAccComputeNetworkFirewallPolicyAssociation_GlobalHandWritten(t *testing CheckDestroy: testAccCheckComputeNetworkFirewallPolicyAssociationDestroyProducer(t), Steps: []resource.TestStep{ { - Config: testAccComputeNetworkFirewallPolicyAssociation_GlobalHandWritten(context), - }, - { - ResourceName: "google_compute_network_firewall_policy_association.primary", - ImportState: true, - ImportStateVerify: true, - }, - { - Config: testAccComputeNetworkFirewallPolicyAssociation_GlobalHandWrittenUpdate0(context), + Config: testAccComputeNetworkFirewallPolicyAssociation_networkFirewallPolicyAssociationExample(context), }, { - ResourceName: "google_compute_network_firewall_policy_association.primary", - ImportState: true, - ImportStateVerify: true, + ResourceName: "google_compute_network_firewall_policy_association.default", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"firewall_policy"}, }, }, }) } -func testAccComputeNetworkFirewallPolicyAssociation_GlobalHandWritten(context map[string]interface{}) string { +func testAccComputeNetworkFirewallPolicyAssociation_networkFirewallPolicyAssociationExample(context map[string]interface{}) string { return acctest.Nprintf(` -resource "google_compute_network_firewall_policy" "network_firewall_policy" { - name = "tf-test-policy%{random_suffix}" +resource "google_compute_network_firewall_policy" "policy" { + name = "tf-test-my-policy%{random_suffix}" project = "%{project_name}" description = "Sample global network firewall policy" } resource "google_compute_network" "network" { - name = "tf-test-network%{random_suffix}" -} - -resource "google_compute_network_firewall_policy_association" "primary" { - name = "tf-test-association%{random_suffix}" - attachment_target = google_compute_network.network.id - firewall_policy = google_compute_network_firewall_policy.network_firewall_policy.name - project = "%{project_name}" + name = "tf-test-my-network%{random_suffix}" + auto_create_subnetworks = false } -`, context) -} - -func testAccComputeNetworkFirewallPolicyAssociation_GlobalHandWrittenUpdate0(context map[string]interface{}) string { - return acctest.Nprintf(` -resource "google_compute_network_firewall_policy" "network_firewall_policy" { - name = "tf-test-policy%{random_suffix}" +resource "google_compute_network_firewall_policy_association" "default" { + name = "tf-test-my-association%{random_suffix}" project = "%{project_name}" - description = "Sample global network firewall policy" -} - -resource "google_compute_network" "network" { - name = "tf-test-network%{random_suffix}" -} - -resource "google_compute_network" "network2" { - name = "update-tf-test-network%{random_suffix}" -} - -resource "google_compute_network_firewall_policy_association" "primary" { - name = "tf-test-association%{random_suffix}" - attachment_target = google_compute_network.network2.id - firewall_policy = google_compute_network_firewall_policy.network_firewall_policy.name - project = "%{project_name}" + attachment_target = google_compute_network.network.id + firewall_policy = google_compute_network_firewall_policy.policy.id } - `, context) } func testAccCheckComputeNetworkFirewallPolicyAssociationDestroyProducer(t *testing.T) func(s *terraform.State) error { return func(s *terraform.State) error { for name, rs := range s.RootModule().Resources { - if rs.Type != "rs.google_compute_network_firewall_policy_association" { + if rs.Type != "google_compute_network_firewall_policy_association" { continue } if strings.HasPrefix(name, "data.") { @@ -126,25 +91,29 @@ func testAccCheckComputeNetworkFirewallPolicyAssociationDestroyProducer(t *testi config := acctest.GoogleProviderConfig(t) + url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{ComputeBasePath}}projects/{{project}}/global/firewallPolicies/{{firewall_policy}}/getAssociation?name={{name}}") + if err != nil { + return err + } + billingProject := "" + if config.BillingProject != "" { billingProject = config.BillingProject } - obj := &compute.NetworkFirewallPolicyAssociation{ - AttachmentTarget: dcl.String(rs.Primary.Attributes["attachment_target"]), - FirewallPolicy: dcl.String(rs.Primary.Attributes["firewall_policy"]), - Name: dcl.String(rs.Primary.Attributes["name"]), - Project: dcl.StringOrNil(rs.Primary.Attributes["project"]), - ShortName: dcl.StringOrNil(rs.Primary.Attributes["short_name"]), - } - - client := transport_tpg.NewDCLComputeClient(config, config.UserAgent, billingProject, 0) - _, err := client.GetNetworkFirewallPolicyAssociation(context.Background(), obj) + _, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: billingProject, + RawURL: url, + UserAgent: config.UserAgent, + }) if err == nil { - return fmt.Errorf("google_compute_network_firewall_policy_association still exists %v", obj) + return fmt.Errorf("ComputeNetworkFirewallPolicyAssociation still exists at %s", url) } } + return nil } } diff --git a/google-beta/services/compute/resource_compute_network_firewall_policy_association_sweeper.go b/google-beta/services/compute/resource_compute_network_firewall_policy_association_sweeper.go new file mode 100644 index 0000000000..a9acd614d2 --- /dev/null +++ b/google-beta/services/compute/resource_compute_network_firewall_policy_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 compute + +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("ComputeNetworkFirewallPolicyAssociation", testSweepComputeNetworkFirewallPolicyAssociation) +} + +// At the time of writing, the CI only passes us-central1 as the region +func testSweepComputeNetworkFirewallPolicyAssociation(region string) error { + resourceName := "ComputeNetworkFirewallPolicyAssociation" + 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://compute.googleapis.com/compute/beta/projects/{{project}}/global/firewallPolicies/{{firewall_policy}}", "?")[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["networkFirewallPolicyAssociations"] + 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://compute.googleapis.com/compute/beta/projects/{{project}}/global/firewallPolicies/{{firewall_policy}}/removeAssociation?name={{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/compute/resource_compute_network_firewall_policy_rule_test.go b/google-beta/services/compute/resource_compute_network_firewall_policy_rule_test.go index b3a3776837..0160062823 100644 --- a/google-beta/services/compute/resource_compute_network_firewall_policy_rule_test.go +++ b/google-beta/services/compute/resource_compute_network_firewall_policy_rule_test.go @@ -88,6 +88,7 @@ func TestAccComputeNetworkFirewallPolicyRule_multipleRules(t *testing.T) { context := map[string]interface{}{ "random_suffix": acctest.RandString(t, 10), + "project_name": envvar.GetTestProjectFromEnv(), "org_name": fmt.Sprintf("organizations/%s", envvar.GetTestOrgFromEnv(t)), } @@ -733,11 +734,23 @@ resource "google_compute_network_firewall_policy_rule" "fw_policy_rule2" { func testAccComputeNetworkFirewallPolicyRule_multipleAdd(context map[string]interface{}) string { return acctest.Nprintf(` +resource "google_compute_network" "network1" { + name = "tf-test-%{random_suffix}" + auto_create_subnetworks = false +} + resource "google_compute_network_firewall_policy" "fw_policy" { name = "tf-test-policy-%{random_suffix}" description = "Resource created for Terraform acceptance testing" } +resource "google_compute_network_firewall_policy_association" "fw_policy_a" { + name = "tf-test-policy-a-%{random_suffix}" + project = "projects/%{project_name}" + attachment_target = google_compute_network.network1.id + firewall_policy = google_compute_network_firewall_policy.fw_policy.id +} + resource "google_network_security_address_group" "address_group" { name = "tf-test-policy%{random_suffix}" parent = "%{org_name}" @@ -817,11 +830,23 @@ resource "google_compute_network_firewall_policy_rule" "fw_policy_rule3" { func testAccComputeNetworkFirewallPolicyRule_multipleRemove(context map[string]interface{}) string { return acctest.Nprintf(` +resource "google_compute_network" "network1" { + name = "tf-test-%{random_suffix}" + auto_create_subnetworks = false +} + resource "google_compute_network_firewall_policy" "fw_policy" { name = "tf-test-policy-%{random_suffix}" description = "Resource created for Terraform acceptance testing" } +resource "google_compute_network_firewall_policy_association" "fw_policy_a" { + name = "tf-test-policy-a-%{random_suffix}" + project = "%{project_name}" + attachment_target = google_compute_network.network1.id + firewall_policy = google_compute_network_firewall_policy.fw_policy.id +} + resource "google_network_security_address_group" "address_group" { name = "tf-test-policy%{random_suffix}" parent = "%{org_name}" diff --git a/google-beta/services/compute/resource_compute_region_network_firewall_policy_association.go b/google-beta/services/compute/resource_compute_region_network_firewall_policy_association.go index bb61f275ab..313f148770 100644 --- a/google-beta/services/compute/resource_compute_region_network_firewall_policy_association.go +++ b/google-beta/services/compute/resource_compute_region_network_firewall_policy_association.go @@ -3,34 +3,31 @@ // ---------------------------------------------------------------------------- // -// *** AUTO GENERATED CODE *** Type: DCL *** +// *** AUTO GENERATED CODE *** Type: MMv1 *** // // ---------------------------------------------------------------------------- // -// This file is managed by Magic Modules (https://github.com/GoogleCloudPlatform/magic-modules) -// and is based on the DCL (https://github.com/GoogleCloudPlatform/declarative-resource-client-library). -// Changes will need to be made to the DCL or Magic Modules instead of here. +// This file is automatically generated by Magic Modules and manual +// changes will be clobbered when the file is regenerated. // -// We are not currently able to accept contributions to this file. If changes -// are required, please file an issue at https://github.com/hashicorp/terraform-provider-google/issues/new/choose +// Please read more about how to change this file in +// .github/CONTRIBUTING.md. // // ---------------------------------------------------------------------------- package compute import ( - "context" "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" - dcl "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" - compute "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/compute/beta" - - "github.com/hashicorp/terraform-provider-google-beta/google-beta/tpgdclresource" "github.com/hashicorp/terraform-provider-google-beta/google-beta/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google-beta/google-beta/transport" ) @@ -49,9 +46,9 @@ func ResourceComputeRegionNetworkFirewallPolicyAssociation() *schema.Resource { Create: schema.DefaultTimeout(20 * time.Minute), Delete: schema.DefaultTimeout(20 * time.Minute), }, + CustomizeDiff: customdiff.All( tpgresource.DefaultProviderProject, - tpgresource.DefaultProviderRegion, ), Schema: map[string]*schema.Schema{ @@ -60,164 +57,171 @@ func ResourceComputeRegionNetworkFirewallPolicyAssociation() *schema.Resource { Required: true, ForceNew: true, DiffSuppressFunc: tpgresource.CompareSelfLinkOrResourceName, - Description: "The target that the firewall policy is attached to.", + Description: `The target that the firewall policy is attached to.`, }, - "firewall_policy": { Type: schema.TypeString, Required: true, ForceNew: true, DiffSuppressFunc: tpgresource.CompareSelfLinkOrResourceName, - Description: "The firewall policy ID of the association.", + Description: `The firewall policy of the resource.`, }, - "name": { Type: schema.TypeString, Required: true, ForceNew: true, - Description: "The name for an association.", + Description: `The name for an association.`, }, - - "project": { - Type: schema.TypeString, - Computed: true, - Optional: true, - ForceNew: true, - DiffSuppressFunc: tpgresource.CompareSelfLinkOrResourceName, - Description: "The project for the resource", - }, - "region": { Type: schema.TypeString, Computed: true, Optional: true, ForceNew: true, - Description: "The location of this resource.", + Description: `The location of this resource.`, }, - "short_name": { Type: schema.TypeString, Computed: true, - Description: "The short name of the firewall policy of the association.", + Description: `The short name of the firewall policy of the association.`, + }, + "project": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, }, }, + UseJSONNumber: true, } } func resourceComputeRegionNetworkFirewallPolicyAssociationCreate(d *schema.ResourceData, meta interface{}) error { config := meta.(*transport_tpg.Config) - project, err := tpgresource.GetProject(d, config) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { return err } - region, err := tpgresource.GetRegion(d, config) + + obj := make(map[string]interface{}) + nameProp, err := expandComputeRegionNetworkFirewallPolicyAssociationName(d.Get("name"), d, config) if err != nil { return err + } else if v, ok := d.GetOkExists("name"); !tpgresource.IsEmptyValue(reflect.ValueOf(nameProp)) && (ok || !reflect.DeepEqual(v, nameProp)) { + obj["name"] = nameProp } - - obj := &compute.NetworkFirewallPolicyAssociation{ - AttachmentTarget: dcl.String(d.Get("attachment_target").(string)), - FirewallPolicy: dcl.String(d.Get("firewall_policy").(string)), - Name: dcl.String(d.Get("name").(string)), - Project: dcl.String(project), - Location: dcl.String(region), + attachmentTargetProp, err := expandComputeRegionNetworkFirewallPolicyAssociationAttachmentTarget(d.Get("attachment_target"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("attachment_target"); !tpgresource.IsEmptyValue(reflect.ValueOf(attachmentTargetProp)) && (ok || !reflect.DeepEqual(v, attachmentTargetProp)) { + obj["attachmentTarget"] = attachmentTargetProp } - id, err := tpgresource.ReplaceVarsForId(d, config, "projects/{{project}}/regions/{{region}}/firewallPolicies/{{firewall_policy}}/associations/{{name}}") + url, err := tpgresource.ReplaceVarsForId(d, config, "{{ComputeBasePath}}projects/{{project}}/regions/{{region}}/firewallPolicies/{{firewall_policy}}/addAssociation") if err != nil { - return fmt.Errorf("error constructing id: %s", err) + return err } - d.SetId(id) - directive := tpgdclresource.CreateDirective - userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + + log.Printf("[DEBUG] Creating new RegionNetworkFirewallPolicyAssociation: %#v", obj) + billingProject := "" + + project, err := tpgresource.GetProject(d, config) if err != nil { - return err + return fmt.Errorf("Error fetching project for RegionNetworkFirewallPolicyAssociation: %s", err) } - billingProject := project + billingProject = strings.TrimPrefix(project, "projects/") + // err == nil indicates that the billing_project value was found if bp, err := tpgresource.GetBillingProject(d, config); err == nil { billingProject = bp } - client := transport_tpg.NewDCLComputeClient(config, userAgent, billingProject, d.Timeout(schema.TimeoutCreate)) - if bp, err := tpgresource.ReplaceVars(d, config, client.Config.BasePath); err != nil { - d.SetId("") - return fmt.Errorf("Could not format %q: %w", client.Config.BasePath, err) - } else { - client.Config.BasePath = 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 RegionNetworkFirewallPolicyAssociation: %s", err) + } + + // Store the ID now + id, err := tpgresource.ReplaceVarsForId(d, config, "projects/{{project}}/regions/{{region}}/firewallPolicies/{{firewall_policy}}/associations/{{name}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) } - res, err := client.ApplyNetworkFirewallPolicyAssociation(context.Background(), obj, directive...) + d.SetId(id) + + err = ComputeOperationWaitTime( + config, res, tpgresource.GetResourceNameFromSelfLink(project), "Creating RegionNetworkFirewallPolicyAssociation", userAgent, + d.Timeout(schema.TimeoutCreate)) - if _, ok := err.(dcl.DiffAfterApplyError); ok { - log.Printf("[DEBUG] Diff after apply returned from the DCL: %s", err) - } else if err != nil { + if err != nil { // The resource didn't actually create d.SetId("") - return fmt.Errorf("Error creating NetworkFirewallPolicyAssociation: %s", err) + return fmt.Errorf("Error waiting to create RegionNetworkFirewallPolicyAssociation: %s", err) } - log.Printf("[DEBUG] Finished creating NetworkFirewallPolicyAssociation %q: %#v", d.Id(), res) + log.Printf("[DEBUG] Finished creating RegionNetworkFirewallPolicyAssociation %q: %#v", d.Id(), res) return resourceComputeRegionNetworkFirewallPolicyAssociationRead(d, meta) } func resourceComputeRegionNetworkFirewallPolicyAssociationRead(d *schema.ResourceData, meta interface{}) error { config := meta.(*transport_tpg.Config) - project, err := tpgresource.GetProject(d, config) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { return err } - region, err := tpgresource.GetRegion(d, config) + + url, err := tpgresource.ReplaceVarsForId(d, config, "{{ComputeBasePath}}projects/{{project}}/regions/{{region}}/firewallPolicies/{{firewall_policy}}/getAssociation?name={{name}}") if err != nil { return err } - obj := &compute.NetworkFirewallPolicyAssociation{ - AttachmentTarget: dcl.String(d.Get("attachment_target").(string)), - FirewallPolicy: dcl.String(d.Get("firewall_policy").(string)), - Name: dcl.String(d.Get("name").(string)), - Project: dcl.String(project), - Location: dcl.String(region), - } + billingProject := "" - userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + project, err := tpgresource.GetProject(d, config) if err != nil { - return err + return fmt.Errorf("Error fetching project for RegionNetworkFirewallPolicyAssociation: %s", err) } - billingProject := project + billingProject = strings.TrimPrefix(project, "projects/") + // err == nil indicates that the billing_project value was found if bp, err := tpgresource.GetBillingProject(d, config); err == nil { billingProject = bp } - client := transport_tpg.NewDCLComputeClient(config, userAgent, billingProject, d.Timeout(schema.TimeoutRead)) - if bp, err := tpgresource.ReplaceVars(d, config, client.Config.BasePath); err != nil { - d.SetId("") - return fmt.Errorf("Could not format %q: %w", client.Config.BasePath, err) - } else { - client.Config.BasePath = bp - } - res, err := client.GetNetworkFirewallPolicyAssociation(context.Background(), obj) + + 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 { - resourceName := fmt.Sprintf("ComputeRegionNetworkFirewallPolicyAssociation %q", d.Id()) - return tpgdclresource.HandleNotFoundDCLError(err, d, resourceName) + return transport_tpg.HandleNotFoundError(err, d, fmt.Sprintf("ComputeRegionNetworkFirewallPolicyAssociation %q", d.Id())) } - if err = d.Set("attachment_target", res.AttachmentTarget); err != nil { - return fmt.Errorf("error setting attachment_target in state: %s", err) - } - if err = d.Set("firewall_policy", res.FirewallPolicy); err != nil { - return fmt.Errorf("error setting firewall_policy in state: %s", err) - } - if err = d.Set("name", res.Name); err != nil { - return fmt.Errorf("error setting name in state: %s", err) + if err := d.Set("project", project); err != nil { + return fmt.Errorf("Error reading RegionNetworkFirewallPolicyAssociation: %s", err) } - if err = d.Set("project", res.Project); err != nil { - return fmt.Errorf("error setting project in state: %s", err) + + if err := d.Set("name", flattenComputeRegionNetworkFirewallPolicyAssociationName(res["name"], d, config)); err != nil { + return fmt.Errorf("Error reading RegionNetworkFirewallPolicyAssociation: %s", err) } - if err = d.Set("region", res.Location); err != nil { - return fmt.Errorf("error setting region in state: %s", err) + if err := d.Set("attachment_target", flattenComputeRegionNetworkFirewallPolicyAssociationAttachmentTarget(res["attachmentTarget"], d, config)); err != nil { + return fmt.Errorf("Error reading RegionNetworkFirewallPolicyAssociation: %s", err) } - if err = d.Set("short_name", res.ShortName); err != nil { - return fmt.Errorf("error setting short_name in state: %s", err) + if err := d.Set("short_name", flattenComputeRegionNetworkFirewallPolicyAssociationShortName(res["shortName"], d, config)); err != nil { + return fmt.Errorf("Error reading RegionNetworkFirewallPolicyAssociation: %s", err) } return nil @@ -225,54 +229,68 @@ func resourceComputeRegionNetworkFirewallPolicyAssociationRead(d *schema.Resourc func resourceComputeRegionNetworkFirewallPolicyAssociationDelete(d *schema.ResourceData, meta interface{}) error { config := meta.(*transport_tpg.Config) - project, err := tpgresource.GetProject(d, config) - if err != nil { - return err - } - region, err := tpgresource.GetRegion(d, config) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) if err != nil { return err } - obj := &compute.NetworkFirewallPolicyAssociation{ - AttachmentTarget: dcl.String(d.Get("attachment_target").(string)), - FirewallPolicy: dcl.String(d.Get("firewall_policy").(string)), - Name: dcl.String(d.Get("name").(string)), - Project: dcl.String(project), - Location: dcl.String(region), + billingProject := "" + + project, err := tpgresource.GetProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for RegionNetworkFirewallPolicyAssociation: %s", err) } + billingProject = strings.TrimPrefix(project, "projects/") - log.Printf("[DEBUG] Deleting NetworkFirewallPolicyAssociation %q", d.Id()) - userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + url, err := tpgresource.ReplaceVarsForId(d, config, "{{ComputeBasePath}}projects/{{project}}/regions/{{region}}/firewallPolicies/{{firewall_policy}}/removeAssociation?name={{name}}") if err != nil { return err } - billingProject := project + + 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 } - client := transport_tpg.NewDCLComputeClient(config, userAgent, billingProject, d.Timeout(schema.TimeoutDelete)) - if bp, err := tpgresource.ReplaceVars(d, config, client.Config.BasePath); err != nil { - d.SetId("") - return fmt.Errorf("Could not format %q: %w", client.Config.BasePath, err) - } else { - client.Config.BasePath = bp + + headers := make(http.Header) + + log.Printf("[DEBUG] Deleting RegionNetworkFirewallPolicyAssociation %q", d.Id()) + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: billingProject, + RawURL: url, + UserAgent: userAgent, + Body: obj, + Timeout: d.Timeout(schema.TimeoutDelete), + Headers: headers, + }) + if err != nil { + return transport_tpg.HandleNotFoundError(err, d, "RegionNetworkFirewallPolicyAssociation") } - if err := client.DeleteNetworkFirewallPolicyAssociation(context.Background(), obj); err != nil { - return fmt.Errorf("Error deleting NetworkFirewallPolicyAssociation: %s", err) + + err = ComputeOperationWaitTime( + config, res, tpgresource.GetResourceNameFromSelfLink(project), "Deleting RegionNetworkFirewallPolicyAssociation", userAgent, + d.Timeout(schema.TimeoutDelete)) + + if err != nil { + return err } - log.Printf("[DEBUG] Finished deleting NetworkFirewallPolicyAssociation %q", d.Id()) + log.Printf("[DEBUG] Finished deleting RegionNetworkFirewallPolicyAssociation %q: %#v", d.Id(), res) return nil } func resourceComputeRegionNetworkFirewallPolicyAssociationImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { config := meta.(*transport_tpg.Config) - if err := tpgresource.ParseImportId([]string{ - "projects/(?P[^/]+)/regions/(?P[^/]+)/firewallPolicies/(?P[^/]+)/associations/(?P[^/]+)", - "(?P[^/]+)/(?P[^/]+)/(?P[^/]+)/(?P[^/]+)", + "^projects/(?P[^/]+)/regions/(?P[^/]+)/firewallPolicies/(?P[^/]+)/associations/(?P[^/]+)$", + "^(?P[^/]+)/(?P[^/]+)/(?P[^/]+)/(?P[^/]+)$", + "^(?P[^/]+)/(?P[^/]+)/(?P[^/]+)$", + "^(?P[^/]+)/(?P[^/]+)/(?P[^/]+)$", + "^(?P[^/]+)/(?P[^/]+)$", }, d, config); err != nil { return nil, err } @@ -286,3 +304,23 @@ func resourceComputeRegionNetworkFirewallPolicyAssociationImport(d *schema.Resou return []*schema.ResourceData{d}, nil } + +func flattenComputeRegionNetworkFirewallPolicyAssociationName(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenComputeRegionNetworkFirewallPolicyAssociationAttachmentTarget(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenComputeRegionNetworkFirewallPolicyAssociationShortName(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func expandComputeRegionNetworkFirewallPolicyAssociationName(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandComputeRegionNetworkFirewallPolicyAssociationAttachmentTarget(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} diff --git a/google-beta/services/compute/resource_compute_region_network_firewall_policy_association_generated_test.go b/google-beta/services/compute/resource_compute_region_network_firewall_policy_association_generated_test.go index 6acb6e6c53..621a2a8d30 100644 --- a/google-beta/services/compute/resource_compute_region_network_firewall_policy_association_generated_test.go +++ b/google-beta/services/compute/resource_compute_region_network_firewall_policy_association_generated_test.go @@ -3,37 +3,35 @@ // ---------------------------------------------------------------------------- // -// *** AUTO GENERATED CODE *** Type: DCL *** +// *** AUTO GENERATED CODE *** Type: MMv1 *** // // ---------------------------------------------------------------------------- // -// This file is managed by Magic Modules (https://github.com/GoogleCloudPlatform/magic-modules) -// and is based on the DCL (https://github.com/GoogleCloudPlatform/declarative-resource-client-library). -// Changes will need to be made to the DCL or Magic Modules instead of here. +// This file is automatically generated by Magic Modules and manual +// changes will be clobbered when the file is regenerated. // -// We are not currently able to accept contributions to this file. If changes -// are required, please file an issue at https://github.com/hashicorp/terraform-provider-google/issues/new/choose +// Please read more about how to change this file in +// .github/CONTRIBUTING.md. // // ---------------------------------------------------------------------------- package compute_test import ( - "context" "fmt" - dcl "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" - compute "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/compute/beta" - "github.com/hashicorp/terraform-plugin-testing/helper/resource" - "github.com/hashicorp/terraform-plugin-testing/terraform" "strings" "testing" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" + "github.com/hashicorp/terraform-provider-google-beta/google-beta/acctest" "github.com/hashicorp/terraform-provider-google-beta/google-beta/envvar" + "github.com/hashicorp/terraform-provider-google-beta/google-beta/tpgresource" transport_tpg "github.com/hashicorp/terraform-provider-google-beta/google-beta/transport" ) -func TestAccComputeRegionNetworkFirewallPolicyAssociation_RegionalHandWritten(t *testing.T) { +func TestAccComputeRegionNetworkFirewallPolicyAssociation_regionNetworkFirewallPolicyAssociationExample(t *testing.T) { t.Parallel() context := map[string]interface{}{ @@ -48,81 +46,46 @@ func TestAccComputeRegionNetworkFirewallPolicyAssociation_RegionalHandWritten(t CheckDestroy: testAccCheckComputeRegionNetworkFirewallPolicyAssociationDestroyProducer(t), Steps: []resource.TestStep{ { - Config: testAccComputeRegionNetworkFirewallPolicyAssociation_RegionalHandWritten(context), - }, - { - ResourceName: "google_compute_region_network_firewall_policy_association.primary", - ImportState: true, - ImportStateVerify: true, - }, - { - Config: testAccComputeRegionNetworkFirewallPolicyAssociation_RegionalHandWrittenUpdate0(context), + Config: testAccComputeRegionNetworkFirewallPolicyAssociation_regionNetworkFirewallPolicyAssociationExample(context), }, { - ResourceName: "google_compute_region_network_firewall_policy_association.primary", - ImportState: true, - ImportStateVerify: true, + ResourceName: "google_compute_region_network_firewall_policy_association.default", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"firewall_policy", "region"}, }, }, }) } -func testAccComputeRegionNetworkFirewallPolicyAssociation_RegionalHandWritten(context map[string]interface{}) string { +func testAccComputeRegionNetworkFirewallPolicyAssociation_regionNetworkFirewallPolicyAssociationExample(context map[string]interface{}) string { return acctest.Nprintf(` -resource "google_compute_region_network_firewall_policy" "basic_regional_network_firewall_policy" { - name = "tf-test-policy%{random_suffix}" +resource "google_compute_region_network_firewall_policy" "policy" { + name = "tf-test-my-policy%{random_suffix}" project = "%{project_name}" description = "Sample global network firewall policy" region = "%{region}" } -resource "google_compute_network" "basic_network" { - name = "tf-test-network%{random_suffix}" -} - -resource "google_compute_region_network_firewall_policy_association" "primary" { - name = "tf-test-association%{random_suffix}" - attachment_target = google_compute_network.basic_network.id - firewall_policy = google_compute_region_network_firewall_policy.basic_regional_network_firewall_policy.name - project = "%{project_name}" - region = "%{region}" -} - -`, context) +resource "google_compute_network" "network" { + name = "tf-test-my-network%{random_suffix}" + auto_create_subnetworks = false } -func testAccComputeRegionNetworkFirewallPolicyAssociation_RegionalHandWrittenUpdate0(context map[string]interface{}) string { - return acctest.Nprintf(` -resource "google_compute_region_network_firewall_policy" "basic_regional_network_firewall_policy" { - name = "tf-test-policy%{random_suffix}" +resource "google_compute_region_network_firewall_policy_association" "default" { + name = "tf-test-my-association%{random_suffix}" project = "%{project_name}" - description = "Sample global network firewall policy" - region = "%{region}" -} - -resource "google_compute_network" "basic_network" { - name = "tf-test-network%{random_suffix}" -} - -resource "google_compute_network" "basic_network2" { - name = "update-tf-test-network%{random_suffix}" -} - -resource "google_compute_region_network_firewall_policy_association" "primary" { - name = "tf-test-association%{random_suffix}" - attachment_target = google_compute_network.basic_network2.id - firewall_policy = google_compute_region_network_firewall_policy.basic_regional_network_firewall_policy.name - project = "%{project_name}" + attachment_target = google_compute_network.network.id + firewall_policy = google_compute_region_network_firewall_policy.policy.id region = "%{region}" } - `, context) } func testAccCheckComputeRegionNetworkFirewallPolicyAssociationDestroyProducer(t *testing.T) func(s *terraform.State) error { return func(s *terraform.State) error { for name, rs := range s.RootModule().Resources { - if rs.Type != "rs.google_compute_region_network_firewall_policy_association" { + if rs.Type != "google_compute_region_network_firewall_policy_association" { continue } if strings.HasPrefix(name, "data.") { @@ -131,26 +94,29 @@ func testAccCheckComputeRegionNetworkFirewallPolicyAssociationDestroyProducer(t config := acctest.GoogleProviderConfig(t) + url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{ComputeBasePath}}projects/{{project}}/regions/{{region}}/firewallPolicies/{{firewall_policy}}/getAssociation?name={{name}}") + if err != nil { + return err + } + billingProject := "" + if config.BillingProject != "" { billingProject = config.BillingProject } - obj := &compute.NetworkFirewallPolicyAssociation{ - AttachmentTarget: dcl.String(rs.Primary.Attributes["attachment_target"]), - FirewallPolicy: dcl.String(rs.Primary.Attributes["firewall_policy"]), - Name: dcl.String(rs.Primary.Attributes["name"]), - Project: dcl.StringOrNil(rs.Primary.Attributes["project"]), - Location: dcl.StringOrNil(rs.Primary.Attributes["region"]), - ShortName: dcl.StringOrNil(rs.Primary.Attributes["short_name"]), - } - - client := transport_tpg.NewDCLComputeClient(config, config.UserAgent, billingProject, 0) - _, err := client.GetNetworkFirewallPolicyAssociation(context.Background(), obj) + _, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: billingProject, + RawURL: url, + UserAgent: config.UserAgent, + }) if err == nil { - return fmt.Errorf("google_compute_region_network_firewall_policy_association still exists %v", obj) + return fmt.Errorf("ComputeRegionNetworkFirewallPolicyAssociation still exists at %s", url) } } + return nil } } diff --git a/google-beta/services/compute/resource_compute_region_network_firewall_policy_association_sweeper.go b/google-beta/services/compute/resource_compute_region_network_firewall_policy_association_sweeper.go new file mode 100644 index 0000000000..d48d1d1ce0 --- /dev/null +++ b/google-beta/services/compute/resource_compute_region_network_firewall_policy_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 compute + +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("ComputeRegionNetworkFirewallPolicyAssociation", testSweepComputeRegionNetworkFirewallPolicyAssociation) +} + +// At the time of writing, the CI only passes us-central1 as the region +func testSweepComputeRegionNetworkFirewallPolicyAssociation(region string) error { + resourceName := "ComputeRegionNetworkFirewallPolicyAssociation" + 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://compute.googleapis.com/compute/beta/projects/{{project}}/regions/{{region}}/firewallPolicies/{{firewall_policy}}", "?")[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["regionNetworkFirewallPolicyAssociations"] + 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://compute.googleapis.com/compute/beta/projects/{{project}}/regions/{{region}}/firewallPolicies/{{firewall_policy}}/removeAssociation?name={{name}}" + deleteUrl, err := tpgresource.ReplaceVars(d, config, deleteTemplate) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] error preparing delete url: %s", err) + return nil + } + deleteUrl = deleteUrl + name + + // Don't wait on operations as we may have a lot to delete + _, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "DELETE", + Project: config.Project, + RawURL: deleteUrl, + UserAgent: config.UserAgent, + }) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] Error deleting for url %s : %s", deleteUrl, err) + } else { + log.Printf("[INFO][SWEEPER_LOG] Sent delete request for %s resource: %s", resourceName, name) + } + } + + if nonPrefixCount > 0 { + log.Printf("[INFO][SWEEPER_LOG] %d items were non-sweepable and skipped.", nonPrefixCount) + } + + return nil +} diff --git a/website/docs/r/compute_network_firewall_policy_association.html.markdown b/website/docs/r/compute_network_firewall_policy_association.html.markdown index fa4d22abcf..4810733633 100644 --- a/website/docs/r/compute_network_firewall_policy_association.html.markdown +++ b/website/docs/r/compute_network_firewall_policy_association.html.markdown @@ -1,16 +1,15 @@ --- # ---------------------------------------------------------------------------- # -# *** AUTO GENERATED CODE *** Type: DCL *** +# *** AUTO GENERATED CODE *** Type: MMv1 *** # # ---------------------------------------------------------------------------- # -# This file is managed by Magic Modules (https:#github.com/GoogleCloudPlatform/magic-modules) -# and is based on the DCL (https:#github.com/GoogleCloudPlatform/declarative-resource-client-library). -# Changes will need to be made to the DCL or Magic Modules instead of here. +# This file is automatically generated by Magic Modules and manual +# changes will be clobbered when the file is regenerated. # -# We are not currently able to accept contributions to this file. If changes -# are required, please file an issue at https:#github.com/hashicorp/terraform-provider-google/issues/new/choose +# Please read more about how to change this file in +# .github/CONTRIBUTING.md. # # ---------------------------------------------------------------------------- subcategory: "Compute Engine" @@ -22,51 +21,57 @@ description: |- The Compute NetworkFirewallPolicyAssociation resource -## Example Usage - global + +To get more information about NetworkFirewallPolicyAssociation, see: + +* [API documentation](https://cloud.google.com/compute/docs/reference/rest/v1/networkFirewallPolicies/addAssociation) + +## Example Usage - Network Firewall Policy Association + + ```hcl -resource "google_compute_network_firewall_policy" "network_firewall_policy" { - name = "policy" +resource "google_compute_network_firewall_policy" "policy" { + name = "my-policy" project = "my-project-name" description = "Sample global network firewall policy" } resource "google_compute_network" "network" { - name = "network" + name = "my-network" + auto_create_subnetworks = false } -resource "google_compute_network_firewall_policy_association" "primary" { - name = "association" +resource "google_compute_network_firewall_policy_association" "default" { + name = "my-association" + project = "my-project-name" attachment_target = google_compute_network.network.id - firewall_policy = google_compute_network_firewall_policy.network_firewall_policy.name - project = "my-project-name" + firewall_policy = google_compute_network_firewall_policy.policy.id } - ``` ## Argument Reference The following arguments are supported: + +* `name` - + (Required) + The name for an association. + * `attachment_target` - (Required) The target that the firewall policy is attached to. - + * `firewall_policy` - (Required) - The firewall policy ID of the association. - -* `name` - - (Required) - The name for an association. - + The firewall policy of the resource. - - - -* `project` - - (Optional) - The project for the resource - + +* `project` - (Optional) The ID of the project in which the resource belongs. + If it is not provided, the provider project is used. ## Attributes Reference @@ -77,7 +82,8 @@ In addition to the arguments listed above, the following computed attributes are * `short_name` - The short name of the firewall policy of the association. - + + ## Timeouts This resource provides the following @@ -88,12 +94,15 @@ This resource provides the following ## Import + NetworkFirewallPolicyAssociation can be imported using any of these accepted formats: + * `projects/{{project}}/global/firewallPolicies/{{firewall_policy}}/associations/{{name}}` * `{{project}}/{{firewall_policy}}/{{name}}` +* `{{firewall_policy}}/{{name}}` -In Terraform v1.5.0 and later, use an [`import` block](https://developer.hashicorp.com/terraform/language/import) to import NetworkFirewallPolicyAssociation using one of the formats above. For example: +In Terraform v1.5.0 and later, use an [`import` block](https://developer.hashicorp.com/terraform/language/import) to import NetworkFirewallPolicyAssociation using one of the formats above. For example: ```tf import { @@ -107,7 +116,9 @@ When using the [`terraform import` command](https://developer.hashicorp.com/terr ``` $ terraform import google_compute_network_firewall_policy_association.default projects/{{project}}/global/firewallPolicies/{{firewall_policy}}/associations/{{name}} $ terraform import google_compute_network_firewall_policy_association.default {{project}}/{{firewall_policy}}/{{name}} +$ terraform import google_compute_network_firewall_policy_association.default {{firewall_policy}}/{{name}} ``` +## User Project Overrides - +This resource supports [User Project Overrides](https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/provider_reference#user_project_override). diff --git a/website/docs/r/compute_region_network_firewall_policy_association.html.markdown b/website/docs/r/compute_region_network_firewall_policy_association.html.markdown index a85a2dea85..5ef73f5dbf 100644 --- a/website/docs/r/compute_region_network_firewall_policy_association.html.markdown +++ b/website/docs/r/compute_region_network_firewall_policy_association.html.markdown @@ -1,16 +1,15 @@ --- # ---------------------------------------------------------------------------- # -# *** AUTO GENERATED CODE *** Type: DCL *** +# *** AUTO GENERATED CODE *** Type: MMv1 *** # # ---------------------------------------------------------------------------- # -# This file is managed by Magic Modules (https:#github.com/GoogleCloudPlatform/magic-modules) -# and is based on the DCL (https:#github.com/GoogleCloudPlatform/declarative-resource-client-library). -# Changes will need to be made to the DCL or Magic Modules instead of here. +# This file is automatically generated by Magic Modules and manual +# changes will be clobbered when the file is regenerated. # -# We are not currently able to accept contributions to this file. If changes -# are required, please file an issue at https:#github.com/hashicorp/terraform-provider-google/issues/new/choose +# Please read more about how to change this file in +# .github/CONTRIBUTING.md. # # ---------------------------------------------------------------------------- subcategory: "Compute Engine" @@ -22,57 +21,63 @@ description: |- The Compute NetworkFirewallPolicyAssociation resource -## Example Usage - regional + +To get more information about RegionNetworkFirewallPolicyAssociation, see: + +* [API documentation](https://cloud.google.com/compute/docs/reference/rest/v1/regionNetworkFirewallPolicies/addAssociation) + +## Example Usage - Region Network Firewall Policy Association + + ```hcl -resource "google_compute_region_network_firewall_policy" "basic_regional_network_firewall_policy" { - name = "policy" +resource "google_compute_region_network_firewall_policy" "policy" { + name = "my-policy" project = "my-project-name" description = "Sample global network firewall policy" region = "us-west1" } -resource "google_compute_network" "basic_network" { - name = "network" +resource "google_compute_network" "network" { + name = "my-network" + auto_create_subnetworks = false } -resource "google_compute_region_network_firewall_policy_association" "primary" { - name = "association" - attachment_target = google_compute_network.basic_network.id - firewall_policy = google_compute_region_network_firewall_policy.basic_regional_network_firewall_policy.name - project = "my-project-name" +resource "google_compute_region_network_firewall_policy_association" "default" { + name = "my-association" + project = "my-project-name" + attachment_target = google_compute_network.network.id + firewall_policy = google_compute_region_network_firewall_policy.policy.id region = "us-west1" } - ``` ## Argument Reference The following arguments are supported: + +* `name` - + (Required) + The name for an association. + * `attachment_target` - (Required) The target that the firewall policy is attached to. - + * `firewall_policy` - (Required) - The firewall policy ID of the association. - -* `name` - - (Required) - The name for an association. - + The firewall policy of the resource. - - - + * `region` - (Optional) The location of this resource. - -* `project` - - (Optional) - The project for the resource - + +* `project` - (Optional) The ID of the project in which the resource belongs. + If it is not provided, the provider project is used. ## Attributes Reference @@ -83,7 +88,8 @@ In addition to the arguments listed above, the following computed attributes are * `short_name` - The short name of the firewall policy of the association. - + + ## Timeouts This resource provides the following @@ -94,12 +100,17 @@ This resource provides the following ## Import -NetworkFirewallPolicyAssociation can be imported using any of these accepted formats: + +RegionNetworkFirewallPolicyAssociation can be imported using any of these accepted formats: + * `projects/{{project}}/regions/{{region}}/firewallPolicies/{{firewall_policy}}/associations/{{name}}` * `{{project}}/{{region}}/{{firewall_policy}}/{{name}}` +* `{{region}}/{{firewall_policy}}/{{name}}` +* `{{project}}/{{firewall_policy}}/{{name}}` +* `{{firewall_policy}}/{{name}}` -In Terraform v1.5.0 and later, use an [`import` block](https://developer.hashicorp.com/terraform/language/import) to import NetworkFirewallPolicyAssociation using one of the formats above. For example: +In Terraform v1.5.0 and later, use an [`import` block](https://developer.hashicorp.com/terraform/language/import) to import RegionNetworkFirewallPolicyAssociation using one of the formats above. For example: ```tf import { @@ -108,12 +119,16 @@ import { } ``` -When using the [`terraform import` command](https://developer.hashicorp.com/terraform/cli/commands/import), NetworkFirewallPolicyAssociation can be imported using one of the formats above. For example: +When using the [`terraform import` command](https://developer.hashicorp.com/terraform/cli/commands/import), RegionNetworkFirewallPolicyAssociation can be imported using one of the formats above. For example: ``` $ terraform import google_compute_region_network_firewall_policy_association.default projects/{{project}}/regions/{{region}}/firewallPolicies/{{firewall_policy}}/associations/{{name}} $ terraform import google_compute_region_network_firewall_policy_association.default {{project}}/{{region}}/{{firewall_policy}}/{{name}} +$ terraform import google_compute_region_network_firewall_policy_association.default {{region}}/{{firewall_policy}}/{{name}} +$ terraform import google_compute_region_network_firewall_policy_association.default {{project}}/{{firewall_policy}}/{{name}} +$ terraform import google_compute_region_network_firewall_policy_association.default {{firewall_policy}}/{{name}} ``` +## User Project Overrides - +This resource supports [User Project Overrides](https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/provider_reference#user_project_override).