diff --git a/internal/clients/client.go b/internal/clients/client.go index f02c68a88aa4..e7c500c475dd 100644 --- a/internal/clients/client.go +++ b/internal/clients/client.go @@ -425,7 +425,9 @@ func (client *Client) Build(ctx context.Context, o *common.ClientOptions) error if client.Eventhub, err = eventhub.NewClient(o); err != nil { return fmt.Errorf("building clients for Eventhub: %+v", err) } - client.Firewall = firewall.NewClient(o) + if client.Firewall, err = firewall.NewClient(o); err != nil { + return fmt.Errorf("building clients for Firewall: %+v", err) + } if client.FluidRelay, err = fluidrelay.NewClient(o); err != nil { return fmt.Errorf("building clients for FluidRelay: %+v", err) } diff --git a/internal/services/firewall/client/client.go b/internal/services/firewall/client/client.go index 27a16cf219b9..466fac3aca05 100644 --- a/internal/services/firewall/client/client.go +++ b/internal/services/firewall/client/client.go @@ -4,29 +4,26 @@ package client import ( + "fmt" + + network_2023_04_01 "github.com/hashicorp/go-azure-sdk/resource-manager/network/2023-04-01" + "github.com/hashicorp/go-azure-sdk/sdk/client/resourcemanager" "github.com/hashicorp/terraform-provider-azurerm/internal/common" - "github.com/tombuildsstuff/kermit/sdk/network/2022-07-01/network" ) type Client struct { - AzureFirewallsClient *network.AzureFirewallsClient - FirewallPolicyClient *network.FirewallPoliciesClient - FirewallPolicyRuleGroupClient *network.FirewallPolicyRuleCollectionGroupsClient + *network_2023_04_01.Client } -func NewClient(o *common.ClientOptions) *Client { - firewallsClient := network.NewAzureFirewallsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) - o.ConfigureClient(&firewallsClient.Client, o.ResourceManagerAuthorizer) - - policyClient := network.NewFirewallPoliciesClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) - o.ConfigureClient(&policyClient.Client, o.ResourceManagerAuthorizer) - - policyRuleGroupClient := network.NewFirewallPolicyRuleCollectionGroupsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) - o.ConfigureClient(&policyRuleGroupClient.Client, o.ResourceManagerAuthorizer) +func NewClient(o *common.ClientOptions) (*Client, error) { + client, err := network_2023_04_01.NewClientWithBaseURI(o.Environment.ResourceManager, func(c *resourcemanager.Client) { + o.Configure(c, o.Authorizers.ResourceManager) + }) + if err != nil { + return nil, fmt.Errorf("building clients for Network: %+v", err) + } return &Client{ - AzureFirewallsClient: &firewallsClient, - FirewallPolicyClient: &policyClient, - FirewallPolicyRuleGroupClient: &policyRuleGroupClient, - } + Client: client, + }, nil } diff --git a/internal/services/firewall/firewall_application_rule_collection_resource.go b/internal/services/firewall/firewall_application_rule_collection_resource.go index 4614a42c7735..aefdad79faa5 100644 --- a/internal/services/firewall/firewall_application_rule_collection_resource.go +++ b/internal/services/firewall/firewall_application_rule_collection_resource.go @@ -8,7 +8,10 @@ import ( "log" "time" + "github.com/hashicorp/go-azure-helpers/lang/pointer" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" + "github.com/hashicorp/go-azure-sdk/resource-manager/network/2023-04-01/azurefirewalls" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/helpers/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" @@ -19,7 +22,6 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/kermit/sdk/network/2022-07-01/network" ) func resourceFirewallApplicationRuleCollection() *pluginsdk.Resource { @@ -67,8 +69,8 @@ func resourceFirewallApplicationRuleCollection() *pluginsdk.Resource { Type: pluginsdk.TypeString, Required: true, ValidateFunc: validation.StringInSlice([]string{ - string(network.AzureFirewallRCActionTypeAllow), - string(network.AzureFirewallRCActionTypeDeny), + string(azurefirewalls.AzureFirewallRCActionTypeAllow), + string(azurefirewalls.AzureFirewallRCActionTypeDeny), }, false), }, @@ -117,9 +119,9 @@ func resourceFirewallApplicationRuleCollection() *pluginsdk.Resource { Type: pluginsdk.TypeString, Required: true, ValidateFunc: validation.StringInSlice([]string{ - string(network.AzureFirewallApplicationRuleProtocolTypeHTTP), - string(network.AzureFirewallApplicationRuleProtocolTypeHTTPS), - string(network.AzureFirewallApplicationRuleProtocolTypeMssql), + string(azurefirewalls.AzureFirewallApplicationRuleProtocolTypeHTTP), + string(azurefirewalls.AzureFirewallApplicationRuleProtocolTypeHTTPS), + string(azurefirewalls.AzureFirewallApplicationRuleProtocolTypeMssql), }, false), }, "port": { @@ -138,7 +140,8 @@ func resourceFirewallApplicationRuleCollection() *pluginsdk.Resource { } func resourceFirewallApplicationRuleCollectionCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Firewall.AzureFirewallsClient + client := meta.(*clients.Client).Firewall.Client.AzureFirewalls + subscriptionId := meta.(*clients.Client).Account.SubscriptionId ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() @@ -153,29 +156,35 @@ func resourceFirewallApplicationRuleCollectionCreateUpdate(d *pluginsdk.Resource locks.ByName(firewallName, AzureFirewallResourceName) defer locks.UnlockByName(firewallName, AzureFirewallResourceName) - firewall, err := client.Get(ctx, resourceGroup, firewallName) + firewallId := azurefirewalls.NewAzureFirewallID(subscriptionId, resourceGroup, firewallName) + + firewall, err := client.Get(ctx, firewallId) if err != nil { return fmt.Errorf("retrieving Firewall %q (Resource Group %q): %+v", firewallName, resourceGroup, err) } - if firewall.AzureFirewallPropertiesFormat == nil { - return fmt.Errorf("retrieving Application Rule Collections (Firewall %q / Resource Group %q): `properties` was nil", firewallName, resourceGroup) + if firewall.Model == nil { + return fmt.Errorf("retrieving %s: `model` was nil", firewallId) + } + + if firewall.Model.Properties == nil { + return fmt.Errorf("retrieving %s: `props` was nil", firewallId) } - props := *firewall.AzureFirewallPropertiesFormat + props := *firewall.Model.Properties if props.ApplicationRuleCollections == nil { - return fmt.Errorf("retrieving Application Rule Collections (Firewall %q / Resource Group %q): `properties.ApplicationRuleCollections` was nil", firewallName, resourceGroup) + return fmt.Errorf("retrieving %s: `props.ApplicationRuleCollections` was nil", firewallId) } ruleCollections := *props.ApplicationRuleCollections priority := d.Get("priority").(int) - newRuleCollection := network.AzureFirewallApplicationRuleCollection{ + newRuleCollection := azurefirewalls.AzureFirewallApplicationRuleCollection{ Name: utils.String(name), - AzureFirewallApplicationRuleCollectionPropertiesFormat: &network.AzureFirewallApplicationRuleCollectionPropertiesFormat{ - Action: &network.AzureFirewallRCAction{ - Type: network.AzureFirewallRCActionType(d.Get("action").(string)), + Properties: &azurefirewalls.AzureFirewallApplicationRuleCollectionPropertiesFormat{ + Action: &azurefirewalls.AzureFirewallRCAction{ + Type: pointer.To(azurefirewalls.AzureFirewallRCActionType(d.Get("action").(string))), }, - Priority: utils.Int32(int32(priority)), + Priority: utils.Int64(int64(priority)), Rules: applicationRules, }, } @@ -183,13 +192,13 @@ func resourceFirewallApplicationRuleCollectionCreateUpdate(d *pluginsdk.Resource index := -1 var id string for i, v := range ruleCollections { - if v.Name == nil || v.ID == nil { + if v.Name == nil || v.Id == nil { continue } if *v.Name == name { index = i - id = *v.ID + id = *v.Id break } } @@ -208,24 +217,24 @@ func resourceFirewallApplicationRuleCollectionCreateUpdate(d *pluginsdk.Resource ruleCollections = append(ruleCollections, newRuleCollection) } - firewall.AzureFirewallPropertiesFormat.ApplicationRuleCollections = &ruleCollections + firewall.Model.Properties.ApplicationRuleCollections = &ruleCollections - future, err := client.CreateOrUpdate(ctx, resourceGroup, firewallName, firewall) - if err != nil { - return fmt.Errorf("creating/updating Application Rule Collection %q in Firewall %q (Resource Group %q): %+v", name, firewallName, resourceGroup, err) + if err = client.CreateOrUpdateThenPoll(ctx, firewallId, *firewall.Model); err != nil { + return fmt.Errorf("creating/updating Application Rule Collection %q in %s: %+v", name, firewallId, err) } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for creation/update of Application Rule Collection %q of Firewall %q (Resource Group %q): %+v", name, firewallName, resourceGroup, err) - } - - read, err := client.Get(ctx, resourceGroup, firewallName) + read, err := client.Get(ctx, firewallId) if err != nil { return fmt.Errorf("retrieving Firewall %q (Resource Group %q): %+v", firewallName, resourceGroup, err) } + if read.Model == nil { + return fmt.Errorf("retrieving %s: `model` was nil", firewallId) + + } + var collectionID string - if props := read.AzureFirewallPropertiesFormat; props != nil { + if props := read.Model.Properties; props != nil { if collections := props.ApplicationRuleCollections; collections != nil { for _, collection := range *collections { if collection.Name == nil { @@ -233,7 +242,7 @@ func resourceFirewallApplicationRuleCollectionCreateUpdate(d *pluginsdk.Resource } if *collection.Name == name { - collectionID = *collection.ID + collectionID = *collection.Id break } } @@ -249,7 +258,7 @@ func resourceFirewallApplicationRuleCollectionCreateUpdate(d *pluginsdk.Resource } func resourceFirewallApplicationRuleCollectionRead(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Firewall.AzureFirewallsClient + client := meta.(*clients.Client).Firewall.AzureFirewalls ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() @@ -258,26 +267,32 @@ func resourceFirewallApplicationRuleCollectionRead(d *pluginsdk.ResourceData, me return err } - read, err := client.Get(ctx, id.ResourceGroup, id.AzureFirewallName) + firewallId := azurefirewalls.NewAzureFirewallID(id.SubscriptionId, id.ResourceGroup, id.AzureFirewallName) + + read, err := client.Get(ctx, firewallId) if err != nil { - if utils.ResponseWasNotFound(read.Response) { + if response.WasNotFound(read.HttpResponse) { log.Printf("[DEBUG] Azure Firewall %q (Resource Group %q) was not found - removing from state!", id.ApplicationRuleCollectionName, id.ResourceGroup) d.SetId("") return nil } - return fmt.Errorf("retrieving Azure Firewall %q (Resource Group %q): %+v", id.ApplicationRuleCollectionName, id.ResourceGroup, err) + return fmt.Errorf("retrieving %s: %+v", id, err) + } + + if read.Model == nil { + return fmt.Errorf("retrieving Application Rule Collection %q (Firewall %q / Resource Group %q): `model` was nil", id.ApplicationRuleCollectionName, id.AzureFirewallName, id.ResourceGroup) } - if read.AzureFirewallPropertiesFormat == nil { + if read.Model.Properties == nil { return fmt.Errorf("retrieving Application Rule Collection %q (Firewall %q / Resource Group %q): `props` was nil", id.ApplicationRuleCollectionName, id.AzureFirewallName, id.ResourceGroup) } - props := *read.AzureFirewallPropertiesFormat + props := *read.Model.Properties if props.ApplicationRuleCollections == nil { return fmt.Errorf("retrieving Application Rule Collection %q (Firewall %q / Resource Group %q): `props.ApplicationRuleCollections` was nil", id.ApplicationRuleCollectionName, id.AzureFirewallName, id.ResourceGroup) } - var rule *network.AzureFirewallApplicationRuleCollection + var rule *azurefirewalls.AzureFirewallApplicationRuleCollection for _, r := range *props.ApplicationRuleCollections { if r.Name == nil { continue @@ -299,9 +314,9 @@ func resourceFirewallApplicationRuleCollectionRead(d *pluginsdk.ResourceData, me d.Set("azure_firewall_name", id.AzureFirewallName) d.Set("resource_group_name", id.ResourceGroup) - if props := rule.AzureFirewallApplicationRuleCollectionPropertiesFormat; props != nil { + if props := rule.Properties; props != nil { if action := props.Action; action != nil { - d.Set("action", string(action.Type)) + d.Set("action", string(pointer.From(action.Type))) } if priority := props.Priority; priority != nil { @@ -318,7 +333,7 @@ func resourceFirewallApplicationRuleCollectionRead(d *pluginsdk.ResourceData, me } func resourceFirewallApplicationRuleCollectionDelete(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Firewall.AzureFirewallsClient + client := meta.(*clients.Client).Firewall.Client.AzureFirewalls ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() @@ -330,9 +345,11 @@ func resourceFirewallApplicationRuleCollectionDelete(d *pluginsdk.ResourceData, locks.ByName(id.AzureFirewallName, AzureFirewallResourceName) defer locks.UnlockByName(id.AzureFirewallName, AzureFirewallResourceName) - firewall, err := client.Get(ctx, id.ResourceGroup, id.AzureFirewallName) + firewallId := azurefirewalls.NewAzureFirewallID(id.SubscriptionId, id.ResourceGroup, id.AzureFirewallName) + + firewall, err := client.Get(ctx, firewallId) if err != nil { - if utils.ResponseWasNotFound(firewall.Response) { + if response.WasNotFound(firewall.HttpResponse) { // assume deleted return nil } @@ -340,7 +357,11 @@ func resourceFirewallApplicationRuleCollectionDelete(d *pluginsdk.ResourceData, return fmt.Errorf("making Read request on Azure Firewall %s : %+v", *id, err) } - props := firewall.AzureFirewallPropertiesFormat + if firewall.Model == nil { + return fmt.Errorf("retrieving Application Rule Collection %q (Firewall %q / Resource Group %q): `model` was nil", id.ApplicationRuleCollectionName, id.AzureFirewallName, id.ResourceGroup) + } + + props := firewall.Model.Properties if props == nil { return fmt.Errorf("retrieving Application Rule Collection %q (Firewall %q / Resource Group %q): `props` was nil", id.ApplicationRuleCollectionName, id.AzureFirewallName, id.ResourceGroup) } @@ -348,7 +369,7 @@ func resourceFirewallApplicationRuleCollectionDelete(d *pluginsdk.ResourceData, return fmt.Errorf("retrieving Application Rule Collection %q (Firewall %q / Resource Group %q): `props.ApplicationRuleCollections` was nil", id.ApplicationRuleCollectionName, id.AzureFirewallName, id.ResourceGroup) } - applicationRules := make([]network.AzureFirewallApplicationRuleCollection, 0) + applicationRules := make([]azurefirewalls.AzureFirewallApplicationRuleCollection, 0) for _, rule := range *props.ApplicationRuleCollections { if rule.Name == nil { continue @@ -360,20 +381,15 @@ func resourceFirewallApplicationRuleCollectionDelete(d *pluginsdk.ResourceData, } props.ApplicationRuleCollections = &applicationRules - future, err := client.CreateOrUpdate(ctx, id.ResourceGroup, id.AzureFirewallName, firewall) - if err != nil { + if err := client.CreateOrUpdateThenPoll(ctx, firewallId, *firewall.Model); err != nil { return fmt.Errorf("deleting Application Rule Collection %q from Firewall %q (Resource Group %q): %+v", id.ApplicationRuleCollectionName, id.AzureFirewallName, id.ResourceGroup, err) } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for deletion of Application Rule Collection %q from Firewall %q (Resource Group %q): %+v", id.ApplicationRuleCollectionName, id.AzureFirewallName, id.ResourceGroup, err) - } - return nil } -func expandFirewallApplicationRules(inputs []interface{}) (*[]network.AzureFirewallApplicationRule, error) { - outputs := make([]network.AzureFirewallApplicationRule, 0) +func expandFirewallApplicationRules(inputs []interface{}) (*[]azurefirewalls.AzureFirewallApplicationRule, error) { + outputs := make([]azurefirewalls.AzureFirewallApplicationRule, 0) for _, input := range inputs { rule := input.(map[string]interface{}) @@ -385,7 +401,7 @@ func expandFirewallApplicationRules(inputs []interface{}) (*[]network.AzureFirew ruleFqdnTags := rule["fqdn_tags"].([]interface{}) ruleTargetFqdns := rule["target_fqdns"].([]interface{}) - output := network.AzureFirewallApplicationRule{ + output := azurefirewalls.AzureFirewallApplicationRule{ Name: utils.String(ruleName), Description: utils.String(ruleDescription), SourceAddresses: utils.ExpandStringSlice(ruleSourceAddresses), @@ -394,13 +410,13 @@ func expandFirewallApplicationRules(inputs []interface{}) (*[]network.AzureFirew TargetFqdns: utils.ExpandStringSlice(ruleTargetFqdns), } - ruleProtocols := make([]network.AzureFirewallApplicationRuleProtocol, 0) + ruleProtocols := make([]azurefirewalls.AzureFirewallApplicationRuleProtocol, 0) for _, v := range rule["protocol"].([]interface{}) { protocol := v.(map[string]interface{}) port := protocol["port"].(int) - ruleProtocol := network.AzureFirewallApplicationRuleProtocol{ - Port: utils.Int32(int32(port)), - ProtocolType: network.AzureFirewallApplicationRuleProtocolType(protocol["type"].(string)), + ruleProtocol := azurefirewalls.AzureFirewallApplicationRuleProtocol{ + Port: utils.Int64(int64(port)), + ProtocolType: pointer.To(azurefirewalls.AzureFirewallApplicationRuleProtocolType(protocol["type"].(string))), } ruleProtocols = append(ruleProtocols, ruleProtocol) } @@ -420,7 +436,7 @@ func expandFirewallApplicationRules(inputs []interface{}) (*[]network.AzureFirew return &outputs, nil } -func flattenFirewallApplicationRuleCollectionRules(rules *[]network.AzureFirewallApplicationRule) []interface{} { +func flattenFirewallApplicationRuleCollectionRules(rules *[]azurefirewalls.AzureFirewallApplicationRule) []interface{} { outputs := make([]interface{}, 0) if rules == nil { return outputs @@ -453,7 +469,7 @@ func flattenFirewallApplicationRuleCollectionRules(rules *[]network.AzureFirewal if port := p.Port; port != nil { protocol["port"] = int(*port) } - protocol["type"] = string(p.ProtocolType) + protocol["type"] = string(pointer.From(p.ProtocolType)) protocols = append(protocols, protocol) } } diff --git a/internal/services/firewall/firewall_application_rule_collection_resource_test.go b/internal/services/firewall/firewall_application_rule_collection_resource_test.go index 2ad33c89cdff..76829fce0928 100644 --- a/internal/services/firewall/firewall_application_rule_collection_resource_test.go +++ b/internal/services/firewall/firewall_application_rule_collection_resource_test.go @@ -8,14 +8,15 @@ import ( "fmt" "regexp" "testing" + "time" + "github.com/hashicorp/go-azure-sdk/resource-manager/network/2023-04-01/azurefirewalls" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/firewall/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/kermit/sdk/network/2022-07-01/network" ) type FirewallApplicationRuleCollectionResource struct{} @@ -391,16 +392,18 @@ func (FirewallApplicationRuleCollectionResource) Exists(ctx context.Context, cli return nil, err } - resp, err := clients.Firewall.AzureFirewallsClient.Get(ctx, id.ResourceGroup, id.AzureFirewallName) + firewallId := azurefirewalls.NewAzureFirewallID(id.SubscriptionId, id.ResourceGroup, id.AzureFirewallName) + + resp, err := clients.Firewall.Client.AzureFirewalls.Get(ctx, firewallId) if err != nil { return nil, fmt.Errorf("retrieving Firewall Application Rule Collection %q (Firewall %q / Resource Group %q): %v", id.ApplicationRuleCollectionName, id.AzureFirewallName, id.ResourceGroup, err) } - if resp.AzureFirewallPropertiesFormat == nil || resp.AzureFirewallPropertiesFormat.ApplicationRuleCollections == nil { + if resp.Model == nil || resp.Model.Properties == nil || resp.Model.Properties.ApplicationRuleCollections == nil { return nil, fmt.Errorf("retrieving Firewall Application Rule Collection %q (Firewall %q / Resource Group %q): properties or collections was nil", id.ApplicationRuleCollectionName, id.AzureFirewallName, id.ResourceGroup) } - for _, rule := range *resp.AzureFirewallPropertiesFormat.ApplicationRuleCollections { + for _, rule := range *resp.Model.Properties.ApplicationRuleCollections { if rule.Name == nil { continue } @@ -431,39 +434,38 @@ func (t FirewallApplicationRuleCollectionResource) doesNotExist(ctx context.Cont } func (t FirewallApplicationRuleCollectionResource) disappears(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) error { - client := clients.Firewall.AzureFirewallsClient + client := clients.Firewall.Client.AzureFirewalls + ctx, cancel := context.WithDeadline(ctx, time.Now().Add(15*time.Minute)) + defer cancel() id, err := parse.FirewallApplicationRuleCollectionID(state.ID) if err != nil { return err } - resp, err := client.Get(ctx, id.ResourceGroup, id.AzureFirewallName) + firewallId := azurefirewalls.NewAzureFirewallID(id.SubscriptionId, id.ResourceGroup, id.AzureFirewallName) + + resp, err := client.Get(ctx, firewallId) if err != nil { return fmt.Errorf("retrieving Firewall Application Rule Collection %q (Firewall %q / Resource Group %q): %v", id.ApplicationRuleCollectionName, id.AzureFirewallName, id.ResourceGroup, err) } - if resp.AzureFirewallPropertiesFormat == nil || resp.AzureFirewallPropertiesFormat.NatRuleCollections == nil { + if resp.Model == nil || resp.Model.Properties == nil || resp.Model.Properties.ApplicationRuleCollections == nil { return fmt.Errorf("retrieving Firewall Application Rule Collection %q (Firewall %q / Resource Group %q): properties or collections was nil", id.ApplicationRuleCollectionName, id.AzureFirewallName, id.ResourceGroup) } - rules := make([]network.AzureFirewallApplicationRuleCollection, 0) - for _, collection := range *resp.AzureFirewallPropertiesFormat.ApplicationRuleCollections { + rules := make([]azurefirewalls.AzureFirewallApplicationRuleCollection, 0) + for _, collection := range *resp.Model.Properties.ApplicationRuleCollections { if *collection.Name != id.ApplicationRuleCollectionName { rules = append(rules, collection) } } - resp.AzureFirewallPropertiesFormat.ApplicationRuleCollections = &rules + resp.Model.Properties.ApplicationRuleCollections = &rules - future, err := client.CreateOrUpdate(ctx, id.ResourceGroup, id.AzureFirewallName, resp) - if err != nil { + if err = client.CreateOrUpdateThenPoll(ctx, firewallId, *resp.Model); err != nil { return fmt.Errorf("removing Firewall Application Rule Collection %q (Firewall %q / Resource Group %q): %v", id.ApplicationRuleCollectionName, id.AzureFirewallName, id.ResourceGroup, err) } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for the removal of Firewall Application Rule Collection %q (Firewall %q / Resource Group %q): %v", id.ApplicationRuleCollectionName, id.AzureFirewallName, id.ResourceGroup, err) - } - return FirewallApplicationRuleCollectionResource{}.doesNotExist(ctx, clients, state) } diff --git a/internal/services/firewall/firewall_data_source.go b/internal/services/firewall/firewall_data_source.go index f6aede5ec42b..6d22b58d7ed5 100644 --- a/internal/services/firewall/firewall_data_source.go +++ b/internal/services/firewall/firewall_data_source.go @@ -7,17 +7,17 @@ import ( "fmt" "time" + "github.com/hashicorp/go-azure-helpers/lang/pointer" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/go-azure-helpers/resourcemanager/tags" "github.com/hashicorp/go-azure-helpers/resourcemanager/zones" + "github.com/hashicorp/go-azure-sdk/resource-manager/network/2023-04-01/azurefirewalls" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/firewall/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/firewall/validate" - "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/kermit/sdk/network/2022-07-01/network" ) func firewallDataSource() *pluginsdk.Resource { @@ -153,15 +153,15 @@ func firewallDataSource() *pluginsdk.Resource { } func firewallDataSourceRead(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Firewall.AzureFirewallsClient + client := meta.(*clients.Client).Firewall.Client.AzureFirewalls subscriptionId := meta.(*clients.Client).Account.SubscriptionId ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id := parse.NewFirewallID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) - read, err := client.Get(ctx, id.ResourceGroup, id.AzureFirewallName) + id := azurefirewalls.NewAzureFirewallID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) + read, err := client.Get(ctx, id) if err != nil { - if utils.ResponseWasNotFound(read.Response) { + if response.WasNotFound(read.HttpResponse) { return fmt.Errorf("%s was not found", id) } @@ -170,44 +170,48 @@ func firewallDataSourceRead(d *pluginsdk.ResourceData, meta interface{}) error { d.SetId(id.ID()) d.Set("name", id.AzureFirewallName) - d.Set("resource_group_name", id.ResourceGroup) - - d.Set("location", location.NormalizeNilable(read.Location)) - d.Set("zones", zones.FlattenUntyped(read.Zones)) - - if props := read.AzureFirewallPropertiesFormat; props != nil { - if err := d.Set("ip_configuration", flattenFirewallIPConfigurations(props.IPConfigurations)); err != nil { - return fmt.Errorf("setting `ip_configuration`: %+v", err) - } - managementIPConfigs := make([]interface{}, 0) - if props.ManagementIPConfiguration != nil { - managementIPConfigs = flattenFirewallIPConfigurations(&[]network.AzureFirewallIPConfiguration{ - *props.ManagementIPConfiguration, - }) - } - if err := d.Set("management_ip_configuration", managementIPConfigs); err != nil { - return fmt.Errorf("setting `management_ip_configuration`: %+v", err) - } - - d.Set("threat_intel_mode", string(props.ThreatIntelMode)) - - if err := d.Set("dns_servers", flattenFirewallDNSServers(props.AdditionalProperties)); err != nil { - return fmt.Errorf("setting `dns_servers`: %+v", err) - } - - if policy := props.FirewallPolicy; policy != nil { - d.Set("firewall_policy_id", policy.ID) + d.Set("resource_group_name", id.ResourceGroupName) + + if model := read.Model; model != nil { + d.Set("location", location.NormalizeNilable(model.Location)) + d.Set("zones", zones.FlattenUntyped(model.Zones)) + + if props := model.Properties; props != nil { + if err := d.Set("ip_configuration", flattenFirewallIPConfigurations(props.IPConfigurations)); err != nil { + return fmt.Errorf("setting `ip_configuration`: %+v", err) + } + managementIPConfigs := make([]interface{}, 0) + if props.ManagementIPConfiguration != nil { + managementIPConfigs = flattenFirewallIPConfigurations(&[]azurefirewalls.AzureFirewallIPConfiguration{ + *props.ManagementIPConfiguration, + }) + } + if err := d.Set("management_ip_configuration", managementIPConfigs); err != nil { + return fmt.Errorf("setting `management_ip_configuration`: %+v", err) + } + + d.Set("threat_intel_mode", string(pointer.From(props.ThreatIntelMode))) + + if err := d.Set("dns_servers", flattenFirewallDNSServers(props.AdditionalProperties)); err != nil { + return fmt.Errorf("setting `dns_servers`: %+v", err) + } + + if policy := props.FirewallPolicy; policy != nil { + d.Set("firewall_policy_id", policy.Id) + } + + if sku := props.Sku; sku != nil { + d.Set("sku_name", string(pointer.From(sku.Name))) + d.Set("sku_tier", string(pointer.From(sku.Tier))) + } + + if err := d.Set("virtual_hub", flattenFirewallVirtualHubSetting(props)); err != nil { + return fmt.Errorf("setting `virtual_hub`: %+v", err) + } } - if sku := props.Sku; sku != nil { - d.Set("sku_name", string(sku.Name)) - d.Set("sku_tier", string(sku.Tier)) - } - - if err := d.Set("virtual_hub", flattenFirewallVirtualHubSetting(props)); err != nil { - return fmt.Errorf("setting `virtual_hub`: %+v", err) - } + return tags.FlattenAndSet(d, model.Tags) } - return tags.FlattenAndSet(d, read.Tags) + return nil } diff --git a/internal/services/firewall/firewall_nat_rule_collection_resource.go b/internal/services/firewall/firewall_nat_rule_collection_resource.go index c14755879183..d6223b688e5c 100644 --- a/internal/services/firewall/firewall_nat_rule_collection_resource.go +++ b/internal/services/firewall/firewall_nat_rule_collection_resource.go @@ -8,7 +8,10 @@ import ( "log" "time" + "github.com/hashicorp/go-azure-helpers/lang/pointer" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" + "github.com/hashicorp/go-azure-sdk/resource-manager/network/2023-04-01/azurefirewalls" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/locks" @@ -18,7 +21,6 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/kermit/sdk/network/2022-07-01/network" ) func resourceFirewallNatRuleCollection() *pluginsdk.Resource { @@ -66,8 +68,8 @@ func resourceFirewallNatRuleCollection() *pluginsdk.Resource { Type: pluginsdk.TypeString, Required: true, ValidateFunc: validation.StringInSlice([]string{ - string(network.AzureFirewallNatRCActionTypeDnat), - string(network.AzureFirewallNatRCActionTypeSnat), + string(azurefirewalls.AzureFirewallNatRCActionTypeDnat), + string(azurefirewalls.AzureFirewallNatRCActionTypeSnat), }, false), }, @@ -120,10 +122,10 @@ func resourceFirewallNatRuleCollection() *pluginsdk.Resource { Elem: &pluginsdk.Schema{ Type: pluginsdk.TypeString, ValidateFunc: validation.StringInSlice([]string{ - string(network.AzureFirewallNetworkRuleProtocolAny), - string(network.AzureFirewallNetworkRuleProtocolICMP), - string(network.AzureFirewallNetworkRuleProtocolTCP), - string(network.AzureFirewallNetworkRuleProtocolUDP), + string(azurefirewalls.AzureFirewallNetworkRuleProtocolAny), + string(azurefirewalls.AzureFirewallNetworkRuleProtocolICMP), + string(azurefirewalls.AzureFirewallNetworkRuleProtocolTCP), + string(azurefirewalls.AzureFirewallNetworkRuleProtocolUDP), }, false), }, }, @@ -135,7 +137,8 @@ func resourceFirewallNatRuleCollection() *pluginsdk.Resource { } func resourceFirewallNatRuleCollectionCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Firewall.AzureFirewallsClient + client := meta.(*clients.Client).Firewall.Client.AzureFirewalls + subscriptionId := meta.(*clients.Client).Account.SubscriptionId ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() @@ -146,18 +149,24 @@ func resourceFirewallNatRuleCollectionCreateUpdate(d *pluginsdk.ResourceData, me locks.ByName(firewallName, AzureFirewallResourceName) defer locks.UnlockByName(firewallName, AzureFirewallResourceName) - firewall, err := client.Get(ctx, resourceGroup, firewallName) + firewallId := azurefirewalls.NewAzureFirewallID(subscriptionId, resourceGroup, firewallName) + + firewall, err := client.Get(ctx, firewallId) if err != nil { return fmt.Errorf("retrieving Firewall %q (Resource Group %q): %+v", firewallName, resourceGroup, err) } - if firewall.AzureFirewallPropertiesFormat == nil { - return fmt.Errorf("expanding Firewall %q (Resource Group %q): `properties` was nil.", firewallName, resourceGroup) + if firewall.Model == nil { + return fmt.Errorf("retrieving %s: `model` was nil", firewallId) } - props := *firewall.AzureFirewallPropertiesFormat - if props.NatRuleCollections == nil { - return fmt.Errorf("expanding Firewall %q (Resource Group %q): `properties.NatRuleCollections` was nil.", firewallName, resourceGroup) + if firewall.Model.Properties == nil { + return fmt.Errorf("retrieving %s: `props` was nil", firewallId) + } + props := *firewall.Model.Properties + + if props.ApplicationRuleCollections == nil { + return fmt.Errorf("retrieving %s: `props.ApplicationRuleCollections` was nil", firewallId) } ruleCollections := *props.NatRuleCollections @@ -166,13 +175,13 @@ func resourceFirewallNatRuleCollectionCreateUpdate(d *pluginsdk.ResourceData, me return fmt.Errorf("expanding Firewall NAT Rules: %+v", err) } priority := d.Get("priority").(int) - newRuleCollection := network.AzureFirewallNatRuleCollection{ + newRuleCollection := azurefirewalls.AzureFirewallNatRuleCollection{ Name: utils.String(name), - AzureFirewallNatRuleCollectionProperties: &network.AzureFirewallNatRuleCollectionProperties{ - Action: &network.AzureFirewallNatRCAction{ - Type: network.AzureFirewallNatRCActionType(d.Get("action").(string)), + Properties: &azurefirewalls.AzureFirewallNatRuleCollectionProperties{ + Action: &azurefirewalls.AzureFirewallNatRCAction{ + Type: pointer.To(azurefirewalls.AzureFirewallNatRCActionType(d.Get("action").(string))), }, - Priority: utils.Int32(int32(priority)), + Priority: utils.Int64(int64(priority)), Rules: natRules, }, } @@ -181,13 +190,13 @@ func resourceFirewallNatRuleCollectionCreateUpdate(d *pluginsdk.ResourceData, me var id string // determine if this already exists for i, v := range ruleCollections { - if v.Name == nil || v.ID == nil { + if v.Name == nil || v.Id == nil { continue } if *v.Name == name { index = i - id = *v.ID + id = *v.Id break } } @@ -207,23 +216,23 @@ func resourceFirewallNatRuleCollectionCreateUpdate(d *pluginsdk.ResourceData, me ruleCollections = append(ruleCollections, newRuleCollection) } - firewall.AzureFirewallPropertiesFormat.NatRuleCollections = &ruleCollections - future, err := client.CreateOrUpdate(ctx, resourceGroup, firewallName, firewall) - if err != nil { + firewall.Model.Properties.NatRuleCollections = &ruleCollections + if err = client.CreateOrUpdateThenPoll(ctx, firewallId, *firewall.Model); err != nil { return fmt.Errorf("creating/updating NAT Rule Collection %q in Firewall %q (Resource Group %q): %+v", name, firewallName, resourceGroup, err) } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for creation/update of NAT Rule Collection %q of Firewall %q (Resource Group %q): %+v", name, firewallName, resourceGroup, err) - } - - read, err := client.Get(ctx, resourceGroup, firewallName) + read, err := client.Get(ctx, firewallId) if err != nil { return fmt.Errorf("retrieving Firewall %q (Resource Group %q): %+v", firewallName, resourceGroup, err) } + if read.Model == nil { + return fmt.Errorf("retrieving %s: `model` was nil", firewallId) + + } + var collectionID string - if props := read.AzureFirewallPropertiesFormat; props != nil { + if props := read.Model.Properties; props != nil { if collections := props.NatRuleCollections; collections != nil { for _, collection := range *collections { if collection.Name == nil { @@ -231,7 +240,7 @@ func resourceFirewallNatRuleCollectionCreateUpdate(d *pluginsdk.ResourceData, me } if *collection.Name == name { - collectionID = *collection.ID + collectionID = *collection.Id break } } @@ -247,7 +256,7 @@ func resourceFirewallNatRuleCollectionCreateUpdate(d *pluginsdk.ResourceData, me } func resourceFirewallNatRuleCollectionRead(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Firewall.AzureFirewallsClient + client := meta.(*clients.Client).Firewall.Client.AzureFirewalls ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() @@ -256,26 +265,33 @@ func resourceFirewallNatRuleCollectionRead(d *pluginsdk.ResourceData, meta inter return err } - read, err := client.Get(ctx, id.ResourceGroup, id.AzureFirewallName) + firewallId := azurefirewalls.NewAzureFirewallID(id.SubscriptionId, id.ResourceGroup, id.AzureFirewallName) + + read, err := client.Get(ctx, firewallId) if err != nil { - if utils.ResponseWasNotFound(read.Response) { + if response.WasNotFound(read.HttpResponse) { log.Printf("[DEBUG] Azure Firewall %s was not found - removing from state!", *id) d.SetId("") return nil } return fmt.Errorf("retrieving Azure Firewall %s : %+v", *id, err) } - if read.AzureFirewallPropertiesFormat == nil { + + if read.Model == nil { + return fmt.Errorf("retrieving NAT Rule Collection %q (Firewall %q / Resource Group %q): `model` was nil", id.NatRuleCollectionName, id.AzureFirewallName, id.ResourceGroup) + } + + if read.Model.Properties == nil { return fmt.Errorf("retrieving NAT Rule Collection %q (Firewall %q / Resource Group %q): `props` was nil", id.NatRuleCollectionName, id.AzureFirewallName, id.ResourceGroup) } - props := *read.AzureFirewallPropertiesFormat + props := *read.Model.Properties if props.NatRuleCollections == nil { return fmt.Errorf("retrieving NAT Rule Collection %q (Firewall %q / Resource Group %q): `props.NetworkRuleCollections` was nil", id.NatRuleCollectionName, id.AzureFirewallName, id.ResourceGroup) } - var rule *network.AzureFirewallNatRuleCollection + var rule *azurefirewalls.AzureFirewallNatRuleCollection for _, r := range *props.NatRuleCollections { if r.Name == nil { continue @@ -297,9 +313,9 @@ func resourceFirewallNatRuleCollectionRead(d *pluginsdk.ResourceData, meta inter d.Set("azure_firewall_name", id.AzureFirewallName) d.Set("resource_group_name", id.ResourceGroup) - if props := rule.AzureFirewallNatRuleCollectionProperties; props != nil { + if props := rule.Properties; props != nil { if action := props.Action; action != nil { - d.Set("action", string(action.Type)) + d.Set("action", string(pointer.From(action.Type))) } if priority := props.Priority; priority != nil { @@ -316,7 +332,7 @@ func resourceFirewallNatRuleCollectionRead(d *pluginsdk.ResourceData, meta inter } func resourceFirewallNatRuleCollectionDelete(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Firewall.AzureFirewallsClient + client := meta.(*clients.Client).Firewall.Client.AzureFirewalls ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() @@ -328,9 +344,11 @@ func resourceFirewallNatRuleCollectionDelete(d *pluginsdk.ResourceData, meta int locks.ByName(id.AzureFirewallName, AzureFirewallResourceName) defer locks.UnlockByName(id.AzureFirewallName, AzureFirewallResourceName) - firewall, err := client.Get(ctx, id.ResourceGroup, id.AzureFirewallName) + firewallId := azurefirewalls.NewAzureFirewallID(id.SubscriptionId, id.ResourceGroup, id.AzureFirewallName) + + firewall, err := client.Get(ctx, firewallId) if err != nil { - if utils.ResponseWasNotFound(firewall.Response) { + if response.WasNotFound(firewall.HttpResponse) { // assume deleted return nil } @@ -338,7 +356,11 @@ func resourceFirewallNatRuleCollectionDelete(d *pluginsdk.ResourceData, meta int return fmt.Errorf("making Read request on Azure Firewall %q (Resource Group %q): %+v", id.AzureFirewallName, id.ResourceGroup, err) } - props := firewall.AzureFirewallPropertiesFormat + if firewall.Model == nil { + return fmt.Errorf("retrieving NAT Rule Collection %q (Firewall %q / Resource Group %q): `model` was nil", id.NatRuleCollectionName, id.AzureFirewallName, id.ResourceGroup) + } + + props := firewall.Model.Properties if props == nil { return fmt.Errorf("retrieving NAT Rule Collection %q (Firewall %q / Resource Group %q): `props` was nil", id.NatRuleCollectionName, id.AzureFirewallName, id.ResourceGroup) } @@ -346,7 +368,7 @@ func resourceFirewallNatRuleCollectionDelete(d *pluginsdk.ResourceData, meta int return fmt.Errorf("retrieving NAT Rule Collection %q (Firewall %q / Resource Group %q): `props.NatRuleCollections` was nil", id.NatRuleCollectionName, id.AzureFirewallName, id.ResourceGroup) } - natRules := make([]network.AzureFirewallNatRuleCollection, 0) + natRules := make([]azurefirewalls.AzureFirewallNatRuleCollection, 0) for _, rule := range *props.NatRuleCollections { if rule.Name == nil { continue @@ -358,20 +380,15 @@ func resourceFirewallNatRuleCollectionDelete(d *pluginsdk.ResourceData, meta int } props.NatRuleCollections = &natRules - future, err := client.CreateOrUpdate(ctx, id.ResourceGroup, id.AzureFirewallName, firewall) - if err != nil { + if err := client.CreateOrUpdateThenPoll(ctx, firewallId, *firewall.Model); err != nil { return fmt.Errorf("deleting NAT Rule Collection %q from Firewall %q (Resource Group %q): %+v", id.NatRuleCollectionName, id.AzureFirewallName, id.ResourceGroup, err) } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for deletion of NAT Rule Collection %q from Firewall %q (Resource Group %q): %+v", id.NatRuleCollectionName, id.AzureFirewallName, id.ResourceGroup, err) - } - return nil } -func expandFirewallNatRules(input []interface{}) (*[]network.AzureFirewallNatRule, error) { - rules := make([]network.AzureFirewallNatRule, 0) +func expandFirewallNatRules(input []interface{}) (*[]azurefirewalls.AzureFirewallNatRule, error) { + rules := make([]azurefirewalls.AzureFirewallNatRule, 0) for _, nwRule := range input { rule := nwRule.(map[string]interface{}) @@ -406,7 +423,7 @@ func expandFirewallNatRules(input []interface{}) (*[]network.AzureFirewallNatRul translatedAddress := rule["translated_address"].(string) translatedPort := rule["translated_port"].(string) - ruleToAdd := network.AzureFirewallNatRule{ + ruleToAdd := azurefirewalls.AzureFirewallNatRule{ Name: utils.String(name), Description: utils.String(description), SourceAddresses: &sourceAddresses, @@ -417,9 +434,9 @@ func expandFirewallNatRules(input []interface{}) (*[]network.AzureFirewallNatRul TranslatedPort: &translatedPort, } - nrProtocols := make([]network.AzureFirewallNetworkRuleProtocol, 0) + nrProtocols := make([]azurefirewalls.AzureFirewallNetworkRuleProtocol, 0) for _, v := range rule["protocols"].([]interface{}) { - s := network.AzureFirewallNetworkRuleProtocol(v.(string)) + s := azurefirewalls.AzureFirewallNetworkRuleProtocol(v.(string)) nrProtocols = append(nrProtocols, s) } ruleToAdd.Protocols = &nrProtocols @@ -429,7 +446,7 @@ func expandFirewallNatRules(input []interface{}) (*[]network.AzureFirewallNatRul return &rules, nil } -func flattenFirewallNatRuleCollectionRules(rules *[]network.AzureFirewallNatRule) []interface{} { +func flattenFirewallNatRuleCollectionRules(rules *[]azurefirewalls.AzureFirewallNatRule) []interface{} { outputs := make([]interface{}, 0) if rules == nil { return outputs diff --git a/internal/services/firewall/firewall_nat_rule_collection_resource_test.go b/internal/services/firewall/firewall_nat_rule_collection_resource_test.go index 687fc44ce0a0..13c5c025b30a 100644 --- a/internal/services/firewall/firewall_nat_rule_collection_resource_test.go +++ b/internal/services/firewall/firewall_nat_rule_collection_resource_test.go @@ -8,14 +8,15 @@ import ( "fmt" "regexp" "testing" + "time" + "github.com/hashicorp/go-azure-sdk/resource-manager/network/2023-04-01/azurefirewalls" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/firewall/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/kermit/sdk/network/2022-07-01/network" ) type FirewallNatRuleCollectionResource struct{} @@ -231,16 +232,18 @@ func (FirewallNatRuleCollectionResource) Exists(ctx context.Context, clients *cl return nil, err } - resp, err := clients.Firewall.AzureFirewallsClient.Get(ctx, id.ResourceGroup, id.AzureFirewallName) + firewallId := azurefirewalls.NewAzureFirewallID(id.SubscriptionId, id.ResourceGroup, id.AzureFirewallName) + + resp, err := clients.Firewall.Client.AzureFirewalls.Get(ctx, firewallId) if err != nil { return nil, fmt.Errorf("retrieving Firewall Nat Rule Collection %q (Firewall %q / Resource Group %q): %v", id.NatRuleCollectionName, id.AzureFirewallName, id.ResourceGroup, err) } - if resp.AzureFirewallPropertiesFormat == nil || resp.AzureFirewallPropertiesFormat.NatRuleCollections == nil { + if resp.Model == nil || resp.Model.Properties == nil || resp.Model.Properties.NatRuleCollections == nil { return nil, fmt.Errorf("retrieving Firewall Nat Rule Collection %q (Firewall %q / Resource Group %q): properties or collections was nil", id.NatRuleCollectionName, id.AzureFirewallName, id.ResourceGroup) } - for _, rule := range *resp.AzureFirewallPropertiesFormat.NatRuleCollections { + for _, rule := range *resp.Model.Properties.NatRuleCollections { if rule.Name == nil { continue } @@ -271,39 +274,38 @@ func (t FirewallNatRuleCollectionResource) doesNotExist(ctx context.Context, cli } func (t FirewallNatRuleCollectionResource) disappears(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) error { - client := clients.Firewall.AzureFirewallsClient + client := clients.Firewall.Client.AzureFirewalls + ctx, cancel := context.WithDeadline(ctx, time.Now().Add(15*time.Minute)) + defer cancel() id, err := parse.FirewallNatRuleCollectionID(state.ID) if err != nil { return err } - resp, err := client.Get(ctx, id.ResourceGroup, id.AzureFirewallName) + firewallId := azurefirewalls.NewAzureFirewallID(id.SubscriptionId, id.ResourceGroup, id.AzureFirewallName) + + resp, err := client.Get(ctx, firewallId) if err != nil { return fmt.Errorf("retrieving Firewall Nat Rule Collection %q (Firewall %q / Resource Group %q): %v", id.NatRuleCollectionName, id.AzureFirewallName, id.ResourceGroup, err) } - if resp.AzureFirewallPropertiesFormat == nil || resp.AzureFirewallPropertiesFormat.NatRuleCollections == nil { + if resp.Model == nil || resp.Model.Properties == nil || resp.Model.Properties.NatRuleCollections == nil { return fmt.Errorf("retrieving Firewall Nat Rule Collection %q (Firewall %q / Resource Group %q): properties or collections was nil", id.NatRuleCollectionName, id.AzureFirewallName, id.ResourceGroup) } - rules := make([]network.AzureFirewallNatRuleCollection, 0) - for _, collection := range *resp.AzureFirewallPropertiesFormat.NatRuleCollections { + rules := make([]azurefirewalls.AzureFirewallNatRuleCollection, 0) + for _, collection := range *resp.Model.Properties.NatRuleCollections { if *collection.Name != id.NatRuleCollectionName { rules = append(rules, collection) } } - resp.AzureFirewallPropertiesFormat.NatRuleCollections = &rules + resp.Model.Properties.NatRuleCollections = &rules - future, err := client.CreateOrUpdate(ctx, id.ResourceGroup, id.AzureFirewallName, resp) - if err != nil { + if err := client.CreateOrUpdateThenPoll(ctx, firewallId, *resp.Model); err != nil { return fmt.Errorf("removing Firewall Nat Rule Collection %q (Firewall %q / Resource Group %q): %v", id.NatRuleCollectionName, id.AzureFirewallName, id.ResourceGroup, err) } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for the removal of Firewall Nat Rule Collection %q (Firewall %q / Resource Group %q): %v", id.NatRuleCollectionName, id.AzureFirewallName, id.ResourceGroup, err) - } - return FirewallNatRuleCollectionResource{}.doesNotExist(ctx, clients, state) } diff --git a/internal/services/firewall/firewall_network_rule_collection_resource.go b/internal/services/firewall/firewall_network_rule_collection_resource.go index c396a5bc7042..417af48ba22b 100644 --- a/internal/services/firewall/firewall_network_rule_collection_resource.go +++ b/internal/services/firewall/firewall_network_rule_collection_resource.go @@ -8,7 +8,10 @@ import ( "log" "time" + "github.com/hashicorp/go-azure-helpers/lang/pointer" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" + "github.com/hashicorp/go-azure-sdk/resource-manager/network/2023-04-01/azurefirewalls" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/locks" @@ -18,7 +21,6 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/kermit/sdk/network/2022-07-01/network" ) func resourceFirewallNetworkRuleCollection() *pluginsdk.Resource { @@ -66,8 +68,8 @@ func resourceFirewallNetworkRuleCollection() *pluginsdk.Resource { Type: pluginsdk.TypeString, Required: true, ValidateFunc: validation.StringInSlice([]string{ - string(network.AzureFirewallRCActionTypeAllow), - string(network.AzureFirewallRCActionTypeDeny), + string(azurefirewalls.AzureFirewallRCActionTypeAllow), + string(azurefirewalls.AzureFirewallRCActionTypeDeny), }, false), }, @@ -122,10 +124,10 @@ func resourceFirewallNetworkRuleCollection() *pluginsdk.Resource { Elem: &pluginsdk.Schema{ Type: pluginsdk.TypeString, ValidateFunc: validation.StringInSlice([]string{ - string(network.AzureFirewallNetworkRuleProtocolAny), - string(network.AzureFirewallNetworkRuleProtocolICMP), - string(network.AzureFirewallNetworkRuleProtocolTCP), - string(network.AzureFirewallNetworkRuleProtocolUDP), + string(azurefirewalls.AzureFirewallNetworkRuleProtocolAny), + string(azurefirewalls.AzureFirewallNetworkRuleProtocolICMP), + string(azurefirewalls.AzureFirewallNetworkRuleProtocolTCP), + string(azurefirewalls.AzureFirewallNetworkRuleProtocolUDP), }, false), }, }, @@ -137,7 +139,8 @@ func resourceFirewallNetworkRuleCollection() *pluginsdk.Resource { } func resourceFirewallNetworkRuleCollectionCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Firewall.AzureFirewallsClient + client := meta.(*clients.Client).Firewall.Client.AzureFirewalls + subscriptionId := meta.(*clients.Client).Account.SubscriptionId ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() @@ -148,15 +151,21 @@ func resourceFirewallNetworkRuleCollectionCreateUpdate(d *pluginsdk.ResourceData locks.ByName(firewallName, AzureFirewallResourceName) defer locks.UnlockByName(firewallName, AzureFirewallResourceName) - firewall, err := client.Get(ctx, resourceGroup, firewallName) + firewallId := azurefirewalls.NewAzureFirewallID(subscriptionId, resourceGroup, firewallName) + + firewall, err := client.Get(ctx, firewallId) if err != nil { return fmt.Errorf("retrieving Firewall %q (Resource Group %q): %+v", firewallName, resourceGroup, err) } - if firewall.AzureFirewallPropertiesFormat == nil { + if firewall.Model == nil { + return fmt.Errorf("expanding Firewall %q (Resource Group %q): `model` was nil.", firewallName, resourceGroup) + } + + if firewall.Model.Properties == nil { return fmt.Errorf("expanding Firewall %q (Resource Group %q): `properties` was nil.", firewallName, resourceGroup) } - props := *firewall.AzureFirewallPropertiesFormat + props := *firewall.Model.Properties if props.NetworkRuleCollections == nil { return fmt.Errorf("expanding Firewall %q (Resource Group %q): `properties.NetworkRuleCollections` was nil.", firewallName, resourceGroup) @@ -168,13 +177,13 @@ func resourceFirewallNetworkRuleCollectionCreateUpdate(d *pluginsdk.ResourceData return fmt.Errorf("expanding Firewall Network Rules: %+v", err) } priority := d.Get("priority").(int) - newRuleCollection := network.AzureFirewallNetworkRuleCollection{ + newRuleCollection := azurefirewalls.AzureFirewallNetworkRuleCollection{ Name: utils.String(name), - AzureFirewallNetworkRuleCollectionPropertiesFormat: &network.AzureFirewallNetworkRuleCollectionPropertiesFormat{ - Action: &network.AzureFirewallRCAction{ - Type: network.AzureFirewallRCActionType(d.Get("action").(string)), + Properties: &azurefirewalls.AzureFirewallNetworkRuleCollectionPropertiesFormat{ + Action: &azurefirewalls.AzureFirewallRCAction{ + Type: pointer.To(azurefirewalls.AzureFirewallRCActionType(d.Get("action").(string))), }, - Priority: utils.Int32(int32(priority)), + Priority: utils.Int64(int64(priority)), Rules: networkRules, }, } @@ -183,13 +192,13 @@ func resourceFirewallNetworkRuleCollectionCreateUpdate(d *pluginsdk.ResourceData var id string // determine if this already exists for i, v := range ruleCollections { - if v.Name == nil || v.ID == nil { + if v.Name == nil || v.Id == nil { continue } if *v.Name == name { index = i - id = *v.ID + id = *v.Id break } } @@ -209,24 +218,24 @@ func resourceFirewallNetworkRuleCollectionCreateUpdate(d *pluginsdk.ResourceData ruleCollections = append(ruleCollections, newRuleCollection) } - firewall.AzureFirewallPropertiesFormat.NetworkRuleCollections = &ruleCollections + firewall.Model.Properties.NetworkRuleCollections = &ruleCollections - future, err := client.CreateOrUpdate(ctx, resourceGroup, firewallName, firewall) - if err != nil { + if err := client.CreateOrUpdateThenPoll(ctx, firewallId, *firewall.Model); err != nil { return fmt.Errorf("creating/updating Network Rule Collection %q in Firewall %q (Resource Group %q): %+v", name, firewallName, resourceGroup, err) } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for creation/update of Network Rule Collection %q of Firewall %q (Resource Group %q): %+v", name, firewallName, resourceGroup, err) - } - - read, err := client.Get(ctx, resourceGroup, firewallName) + read, err := client.Get(ctx, firewallId) if err != nil { return fmt.Errorf("retrieving Firewall %q (Resource Group %q): %+v", firewallName, resourceGroup, err) } + if read.Model == nil { + return fmt.Errorf("retrieving %s: `model` was nil", firewallId) + + } + var collectionID string - if props := read.AzureFirewallPropertiesFormat; props != nil { + if props := read.Model.Properties; props != nil { if collections := props.NetworkRuleCollections; collections != nil { for _, collection := range *collections { if collection.Name == nil { @@ -234,7 +243,7 @@ func resourceFirewallNetworkRuleCollectionCreateUpdate(d *pluginsdk.ResourceData } if *collection.Name == name { - collectionID = *collection.ID + collectionID = *collection.Id break } } @@ -250,7 +259,7 @@ func resourceFirewallNetworkRuleCollectionCreateUpdate(d *pluginsdk.ResourceData } func resourceFirewallNetworkRuleCollectionRead(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Firewall.AzureFirewallsClient + client := meta.(*clients.Client).Firewall.Client.AzureFirewalls ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() @@ -259,9 +268,11 @@ func resourceFirewallNetworkRuleCollectionRead(d *pluginsdk.ResourceData, meta i return err } - read, err := client.Get(ctx, id.ResourceGroup, id.AzureFirewallName) + firewallId := azurefirewalls.NewAzureFirewallID(id.SubscriptionId, id.ResourceGroup, id.AzureFirewallName) + + read, err := client.Get(ctx, firewallId) if err != nil { - if utils.ResponseWasNotFound(read.Response) { + if response.WasNotFound(read.HttpResponse) { log.Printf("[DEBUG] Azure Firewall %s was not found - removing from state!", *id) d.SetId("") return nil @@ -269,16 +280,20 @@ func resourceFirewallNetworkRuleCollectionRead(d *pluginsdk.ResourceData, meta i return fmt.Errorf("retrieving Azure Firewall %s : %+v", *id, err) } - if read.AzureFirewallPropertiesFormat == nil { + if read.Model == nil { + return fmt.Errorf("retrieving Network Rule Collection %q (Firewall %q / Resource Group %q): `model` was nil", id.NetworkRuleCollectionName, id.AzureFirewallName, id.ResourceGroup) + } + + if read.Model.Properties == nil { return fmt.Errorf("retrieving Network Rule Collection %q (Firewall %q / Resource Group %q): `props` was nil", id.NetworkRuleCollectionName, id.AzureFirewallName, id.ResourceGroup) } - props := *read.AzureFirewallPropertiesFormat + props := *read.Model.Properties if props.NetworkRuleCollections == nil { return fmt.Errorf("retrieving Network Rule Collection %q (Firewall %q / Resource Group %q): `props.NetworkRuleCollections` was nil", id.NetworkRuleCollectionName, id.AzureFirewallName, id.ResourceGroup) } - var rule *network.AzureFirewallNetworkRuleCollection + var rule *azurefirewalls.AzureFirewallNetworkRuleCollection for _, r := range *props.NetworkRuleCollections { if r.Name == nil { continue @@ -300,9 +315,9 @@ func resourceFirewallNetworkRuleCollectionRead(d *pluginsdk.ResourceData, meta i d.Set("azure_firewall_name", id.AzureFirewallName) d.Set("resource_group_name", id.ResourceGroup) - if props := rule.AzureFirewallNetworkRuleCollectionPropertiesFormat; props != nil { + if props := rule.Properties; props != nil { if action := props.Action; action != nil { - d.Set("action", string(action.Type)) + d.Set("action", string(pointer.From(action.Type))) } if priority := props.Priority; priority != nil { @@ -319,7 +334,7 @@ func resourceFirewallNetworkRuleCollectionRead(d *pluginsdk.ResourceData, meta i } func resourceFirewallNetworkRuleCollectionDelete(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Firewall.AzureFirewallsClient + client := meta.(*clients.Client).Firewall.Client.AzureFirewalls ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() @@ -331,9 +346,11 @@ func resourceFirewallNetworkRuleCollectionDelete(d *pluginsdk.ResourceData, meta locks.ByName(id.AzureFirewallName, AzureFirewallResourceName) defer locks.UnlockByName(id.AzureFirewallName, AzureFirewallResourceName) - firewall, err := client.Get(ctx, id.ResourceGroup, id.AzureFirewallName) + firewallId := azurefirewalls.NewAzureFirewallID(id.SubscriptionId, id.ResourceGroup, id.AzureFirewallName) + + firewall, err := client.Get(ctx, firewallId) if err != nil { - if utils.ResponseWasNotFound(firewall.Response) { + if response.WasNotFound(firewall.HttpResponse) { // assume deleted return nil } @@ -341,7 +358,11 @@ func resourceFirewallNetworkRuleCollectionDelete(d *pluginsdk.ResourceData, meta return fmt.Errorf("making Read request on Azure Firewall %q (Resource Group %q): %+v", id.AzureFirewallName, id.ResourceGroup, err) } - props := firewall.AzureFirewallPropertiesFormat + if firewall.Model == nil { + return fmt.Errorf("retrieving Network Rule Collection %q (Firewall %q / Resource Group %q): `model` was nil", id.NetworkRuleCollectionName, id.AzureFirewallName, id.ResourceGroup) + } + + props := firewall.Model.Properties if props == nil { return fmt.Errorf("retrieving Network Rule Collection %q (Firewall %q / Resource Group %q): `props` was nil", id.NetworkRuleCollectionName, id.AzureFirewallName, id.ResourceGroup) } @@ -349,7 +370,7 @@ func resourceFirewallNetworkRuleCollectionDelete(d *pluginsdk.ResourceData, meta return fmt.Errorf("retrieving Network Rule Collection %q (Firewall %q / Resource Group %q): `props.NetworkRuleCollections` was nil", id.NetworkRuleCollectionName, id.AzureFirewallName, id.ResourceGroup) } - networkRules := make([]network.AzureFirewallNetworkRuleCollection, 0) + networkRules := make([]azurefirewalls.AzureFirewallNetworkRuleCollection, 0) for _, rule := range *props.NetworkRuleCollections { if rule.Name == nil { continue @@ -361,20 +382,15 @@ func resourceFirewallNetworkRuleCollectionDelete(d *pluginsdk.ResourceData, meta } props.NetworkRuleCollections = &networkRules - future, err := client.CreateOrUpdate(ctx, id.ResourceGroup, id.AzureFirewallName, firewall) - if err != nil { + if err = client.CreateOrUpdateThenPoll(ctx, firewallId, *firewall.Model); err != nil { return fmt.Errorf("deleting Network Rule Collection %q from Firewall %q (Resource Group %q): %+v", id.NetworkRuleCollectionName, id.AzureFirewallName, id.ResourceGroup, err) } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for deletion of Network Rule Collection %q from Firewall %q (Resource Group %q): %+v", id.NetworkRuleCollectionName, id.AzureFirewallName, id.ResourceGroup, err) - } - return nil } -func expandFirewallNetworkRules(input []interface{}) (*[]network.AzureFirewallNetworkRule, error) { - rules := make([]network.AzureFirewallNetworkRule, 0) +func expandFirewallNetworkRules(input []interface{}) (*[]azurefirewalls.AzureFirewallNetworkRule, error) { + rules := make([]azurefirewalls.AzureFirewallNetworkRule, 0) for _, nwRule := range input { rule := nwRule.(map[string]interface{}) @@ -420,7 +436,7 @@ func expandFirewallNetworkRules(input []interface{}) (*[]network.AzureFirewallNe destinationPorts = append(destinationPorts, v.(string)) } - ruleToAdd := network.AzureFirewallNetworkRule{ + ruleToAdd := azurefirewalls.AzureFirewallNetworkRule{ Name: utils.String(name), Description: utils.String(description), SourceAddresses: &sourceAddresses, @@ -431,9 +447,9 @@ func expandFirewallNetworkRules(input []interface{}) (*[]network.AzureFirewallNe DestinationFqdns: &destinationFqdns, } - nrProtocols := make([]network.AzureFirewallNetworkRuleProtocol, 0) + nrProtocols := make([]azurefirewalls.AzureFirewallNetworkRuleProtocol, 0) for _, v := range rule["protocols"].([]interface{}) { - s := network.AzureFirewallNetworkRuleProtocol(v.(string)) + s := azurefirewalls.AzureFirewallNetworkRuleProtocol(v.(string)) nrProtocols = append(nrProtocols, s) } ruleToAdd.Protocols = &nrProtocols @@ -443,7 +459,7 @@ func expandFirewallNetworkRules(input []interface{}) (*[]network.AzureFirewallNe return &rules, nil } -func flattenFirewallNetworkRuleCollectionRules(rules *[]network.AzureFirewallNetworkRule) []interface{} { +func flattenFirewallNetworkRuleCollectionRules(rules *[]azurefirewalls.AzureFirewallNetworkRule) []interface{} { outputs := make([]interface{}, 0) if rules == nil { return outputs diff --git a/internal/services/firewall/firewall_network_rule_collection_resource_test.go b/internal/services/firewall/firewall_network_rule_collection_resource_test.go index ef29df03d070..7bf643034612 100644 --- a/internal/services/firewall/firewall_network_rule_collection_resource_test.go +++ b/internal/services/firewall/firewall_network_rule_collection_resource_test.go @@ -8,14 +8,15 @@ import ( "fmt" "regexp" "testing" + "time" + "github.com/hashicorp/go-azure-sdk/resource-manager/network/2023-04-01/azurefirewalls" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/firewall/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/kermit/sdk/network/2022-07-01/network" ) type FirewallNetworkRuleCollectionResource struct{} @@ -339,16 +340,18 @@ func (FirewallNetworkRuleCollectionResource) Exists(ctx context.Context, clients return nil, err } - resp, err := clients.Firewall.AzureFirewallsClient.Get(ctx, id.ResourceGroup, id.AzureFirewallName) + firewallId := azurefirewalls.NewAzureFirewallID(id.SubscriptionId, id.ResourceGroup, id.AzureFirewallName) + + resp, err := clients.Firewall.Client.AzureFirewalls.Get(ctx, firewallId) if err != nil { return nil, fmt.Errorf("retrieving Firewall Network Rule Collection %q (Firewall %q / Resource Group %q): %v", id.NetworkRuleCollectionName, id.AzureFirewallName, id.ResourceGroup, err) } - if resp.AzureFirewallPropertiesFormat == nil || resp.AzureFirewallPropertiesFormat.NetworkRuleCollections == nil { + if resp.Model == nil || resp.Model.Properties == nil || resp.Model.Properties.NetworkRuleCollections == nil { return nil, fmt.Errorf("retrieving Firewall Network Rule Collection %q (Firewall %q / Resource Group %q): properties or collections was nil", id.NetworkRuleCollectionName, id.AzureFirewallName, id.ResourceGroup) } - for _, rule := range *resp.AzureFirewallPropertiesFormat.NetworkRuleCollections { + for _, rule := range *resp.Model.Properties.NetworkRuleCollections { if rule.Name == nil { continue } @@ -362,23 +365,28 @@ func (FirewallNetworkRuleCollectionResource) Exists(ctx context.Context, clients func (r FirewallNetworkRuleCollectionResource) checkFirewallNetworkRuleCollectionDoesNotExist(collectionName string) acceptance.ClientCheckFunc { return func(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) error { + ctx, cancel := context.WithDeadline(ctx, time.Now().Add(15*time.Minute)) + defer cancel() // Ensure we have enough information in state to look up in API id, err := parse.FirewallNetworkRuleCollectionID(state.ID) if err != nil { return err } - firewallName := id.AzureFirewallName - resourceGroup := id.ResourceGroup + firewallId := azurefirewalls.NewAzureFirewallID(id.SubscriptionId, id.ResourceGroup, id.AzureFirewallName) - read, err := clients.Firewall.AzureFirewallsClient.Get(ctx, resourceGroup, firewallName) + read, err := clients.Firewall.Client.AzureFirewalls.Get(ctx, firewallId) if err != nil { return err } - for _, collection := range *read.AzureFirewallPropertiesFormat.NetworkRuleCollections { + if read.Model == nil || read.Model.Properties == nil || read.Model.Properties.NetworkRuleCollections == nil { + return fmt.Errorf("one of model/properties/networkRuleCollections was nil for %s", firewallId) + } + + for _, collection := range *read.Model.Properties.NetworkRuleCollections { if *collection.Name == collectionName { - return fmt.Errorf("Network Rule Collection %q exists in Firewall %q: %+v", collectionName, firewallName, collection) + return fmt.Errorf("network Rule Collection %q exists in Firewall %q: %+v", collectionName, firewallId.AzureFirewallName, collection) } } @@ -392,35 +400,31 @@ func (FirewallNetworkRuleCollectionResource) Destroy(ctx context.Context, client return nil, err } - name := id.NetworkRuleCollectionName - firewallName := id.AzureFirewallName - resourceGroup := id.ResourceGroup + firewallId := azurefirewalls.NewAzureFirewallID(id.SubscriptionId, id.ResourceGroup, id.AzureFirewallName) - read, err := clients.Firewall.AzureFirewallsClient.Get(ctx, resourceGroup, firewallName) + read, err := clients.Firewall.Client.AzureFirewalls.Get(ctx, firewallId) if err != nil { return utils.Bool(false), err } - rules := make([]network.AzureFirewallNetworkRuleCollection, 0) - for _, collection := range *read.AzureFirewallPropertiesFormat.NetworkRuleCollections { - if *collection.Name != name { + if read.Model == nil || read.Model.Properties == nil || read.Model.Properties.NetworkRuleCollections == nil { + return utils.Bool(false), fmt.Errorf("one of model/properties/networkRuleCollections was nil for %s", firewallId) + } + + rules := make([]azurefirewalls.AzureFirewallNetworkRuleCollection, 0) + for _, collection := range *read.Model.Properties.NetworkRuleCollections { + if *collection.Name != id.NetworkRuleCollectionName { rules = append(rules, collection) } } - read.AzureFirewallPropertiesFormat.NetworkRuleCollections = &rules + read.Model.Properties.NetworkRuleCollections = &rules - future, err := clients.Firewall.AzureFirewallsClient.CreateOrUpdate(ctx, resourceGroup, firewallName, read) - if err != nil { + if err = clients.Firewall.Client.AzureFirewalls.CreateOrUpdateThenPoll(ctx, firewallId, *read.Model); err != nil { return utils.Bool(false), fmt.Errorf("removing Network Rule Collection from Firewall: %+v", err) } - if err = future.WaitForCompletionRef(ctx, clients.Firewall.AzureFirewallsClient.Client); err != nil { - return utils.Bool(false), fmt.Errorf("waiting for the removal of Network Rule Collection from Firewall: %+v", err) - } - - _, err = clients.Firewall.AzureFirewallsClient.Get(ctx, resourceGroup, firewallName) - return utils.Bool(err == nil), err + return utils.Bool(true), nil } func (FirewallNetworkRuleCollectionResource) basic(data acceptance.TestData) string { diff --git a/internal/services/firewall/firewall_policy_data_source.go b/internal/services/firewall/firewall_policy_data_source.go index 48fa1a4fddec..98edf9260fc5 100644 --- a/internal/services/firewall/firewall_policy_data_source.go +++ b/internal/services/firewall/firewall_policy_data_source.go @@ -7,15 +7,16 @@ import ( "fmt" "time" + "github.com/hashicorp/go-azure-helpers/lang/pointer" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/go-azure-helpers/resourcemanager/tags" + "github.com/hashicorp/go-azure-sdk/resource-manager/network/2023-04-01/firewallpolicies" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/firewall/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/firewall/validate" - "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) func FirewallDataSourcePolicy() *pluginsdk.Resource { @@ -118,22 +119,22 @@ func FirewallDataSourcePolicy() *pluginsdk.Resource { }, }, - "tags": tags.SchemaDataSource(), + "tags": commonschema.TagsDataSource(), }, } } func FirewallDataSourcePolicyRead(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Firewall.FirewallPolicyClient + client := meta.(*clients.Client).Firewall.Client.FirewallPolicies subscriptionId := meta.(*clients.Client).Account.SubscriptionId ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id := parse.NewFirewallPolicyID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) + id := firewallpolicies.NewFirewallPolicyID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) - resp, err := client.Get(ctx, id.ResourceGroup, id.Name, "") + resp, err := client.Get(ctx, id, firewallpolicies.DefaultGetOperationOptions()) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { return fmt.Errorf("%s was not found", id) } @@ -142,33 +143,38 @@ func FirewallDataSourcePolicyRead(d *pluginsdk.ResourceData, meta interface{}) e d.SetId(id.ID()) - d.Set("name", id.Name) - d.Set("resource_group_name", id.ResourceGroup) - d.Set("location", location.NormalizeNilable(resp.Location)) - - if prop := resp.FirewallPolicyPropertiesFormat; prop != nil { - basePolicyID := "" - if resp.BasePolicy != nil && resp.BasePolicy.ID != nil { - basePolicyID = *resp.BasePolicy.ID - } - d.Set("base_policy_id", basePolicyID) - if err := d.Set("child_policies", flattenNetworkSubResourceID(prop.ChildPolicies)); err != nil { - return fmt.Errorf(`setting "child_policies": %+v`, err) - } - if err := d.Set("dns", flattenFirewallPolicyDNSSetting(prop.DNSSettings)); err != nil { - return fmt.Errorf(`setting "dns": %+v`, err) - } - if err := d.Set("firewalls", flattenNetworkSubResourceID(prop.Firewalls)); err != nil { - return fmt.Errorf(`setting "firewalls": %+v`, err) - } - if err := d.Set("rule_collection_groups", flattenNetworkSubResourceID(prop.RuleCollectionGroups)); err != nil { - return fmt.Errorf(`setting "rule_collection_groups": %+v`, err) - } - d.Set("threat_intelligence_mode", string(prop.ThreatIntelMode)) - if err := d.Set("threat_intelligence_allowlist", flattenFirewallPolicyThreatIntelWhitelist(resp.ThreatIntelWhitelist)); err != nil { - return fmt.Errorf(`setting "threat_intelligence_allowlist": %+v`, err) + d.Set("name", id.FirewallPolicyName) + d.Set("resource_group_name", id.ResourceGroupName) + + if model := resp.Model; model != nil { + d.Set("location", location.NormalizeNilable(model.Location)) + + if props := model.Properties; props != nil { + basePolicyID := "" + if props.BasePolicy != nil && props.BasePolicy.Id != nil { + basePolicyID = *props.BasePolicy.Id + } + d.Set("base_policy_id", basePolicyID) + if err := d.Set("child_policies", flattenNetworkSubResourceID(props.ChildPolicies)); err != nil { + return fmt.Errorf(`setting "child_policies": %+v`, err) + } + if err := d.Set("dns", flattenFirewallPolicyDNSSetting(props.DnsSettings)); err != nil { + return fmt.Errorf(`setting "dns": %+v`, err) + } + if err := d.Set("firewalls", flattenNetworkSubResourceID(props.Firewalls)); err != nil { + return fmt.Errorf(`setting "firewalls": %+v`, err) + } + if err := d.Set("rule_collection_groups", flattenNetworkSubResourceID(props.RuleCollectionGroups)); err != nil { + return fmt.Errorf(`setting "rule_collection_groups": %+v`, err) + } + d.Set("threat_intelligence_mode", string(pointer.From(props.ThreatIntelMode))) + if err := d.Set("threat_intelligence_allowlist", flattenFirewallPolicyThreatIntelWhitelist(props.ThreatIntelWhitelist)); err != nil { + return fmt.Errorf(`setting "threat_intelligence_allowlist": %+v`, err) + } } + + return tags.FlattenAndSet(d, model.Tags) } - return tags.FlattenAndSet(d, resp.Tags) + return nil } diff --git a/internal/services/firewall/firewall_policy_resource.go b/internal/services/firewall/firewall_policy_resource.go index ac7f996076bd..4834143d111c 100644 --- a/internal/services/firewall/firewall_policy_resource.go +++ b/internal/services/firewall/firewall_policy_resource.go @@ -8,24 +8,24 @@ import ( "log" "time" + "github.com/hashicorp/go-azure-helpers/lang/pointer" "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/go-azure-helpers/resourcemanager/tags" + "github.com/hashicorp/go-azure-sdk/resource-manager/network/2023-04-01/firewallpolicies" "github.com/hashicorp/go-azure-sdk/resource-manager/operationalinsights/2020-08-01/workspaces" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/locks" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/firewall/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/firewall/validate" - "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/suppress" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/kermit/sdk/network/2022-07-01/network" ) const AzureFirewallPolicyResourceName = "azurerm_firewall_policy" @@ -38,7 +38,7 @@ func resourceFirewallPolicy() *pluginsdk.Resource { Delete: resourceFirewallPolicyDelete, Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.FirewallPolicyID(id) + _, err := firewallpolicies.ParseFirewallPolicyID(id) return err }), @@ -54,86 +54,87 @@ func resourceFirewallPolicy() *pluginsdk.Resource { } func resourceFirewallPolicyCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Firewall.FirewallPolicyClient + client := meta.(*clients.Client).Firewall.Client.FirewallPolicies subscriptionId := meta.(*clients.Client).Account.SubscriptionId ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - id := parse.NewFirewallPolicyID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) + id := firewallpolicies.NewFirewallPolicyID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) if d.IsNewResource() { - resp, err := client.Get(ctx, id.ResourceGroup, id.Name, "") + resp, err := client.Get(ctx, id, firewallpolicies.DefaultGetOperationOptions()) if err != nil { - if !utils.ResponseWasNotFound(resp.Response) { + if !response.WasNotFound(resp.HttpResponse) { return fmt.Errorf("checking for existing %s: %+v", id, err) } } - if resp.ID != nil && *resp.ID != "" { - return tf.ImportAsExistsError("azurerm_firewall_policy", *resp.ID) + if resp.Model != nil { + return tf.ImportAsExistsError("azurerm_firewall_policy", id.ID()) } } - expandedIdentity, err := expandFirewallPolicyIdentity(d.Get("identity").([]interface{})) - if err != nil { - return fmt.Errorf("expanding `identity`: %+v", err) - } - props := network.FirewallPolicy{ - FirewallPolicyPropertiesFormat: &network.FirewallPolicyPropertiesFormat{ - ThreatIntelMode: network.AzureFirewallThreatIntelMode(d.Get("threat_intelligence_mode").(string)), + props := firewallpolicies.FirewallPolicy{ + Properties: &firewallpolicies.FirewallPolicyPropertiesFormat{ + ThreatIntelMode: pointer.To(firewallpolicies.AzureFirewallThreatIntelMode(d.Get("threat_intelligence_mode").(string))), ThreatIntelWhitelist: expandFirewallPolicyThreatIntelWhitelist(d.Get("threat_intelligence_allowlist").([]interface{})), - DNSSettings: expandFirewallPolicyDNSSetting(d.Get("dns").([]interface{})), + DnsSettings: expandFirewallPolicyDNSSetting(d.Get("dns").([]interface{})), IntrusionDetection: expandFirewallPolicyIntrusionDetection(d.Get("intrusion_detection").([]interface{})), TransportSecurity: expandFirewallPolicyTransportSecurity(d.Get("tls_certificate").([]interface{})), Insights: expandFirewallPolicyInsights(d.Get("insights").([]interface{})), ExplicitProxy: expandFirewallPolicyExplicitProxy(d.Get("explicit_proxy").([]interface{})), }, - Identity: expandedIdentity, Location: utils.String(location.Normalize(d.Get("location").(string))), Tags: tags.Expand(d.Get("tags").(map[string]interface{})), } + expandedIdentity, err := identity.ExpandSystemAndUserAssignedMap(d.Get("identity").([]interface{})) + if err != nil { + return fmt.Errorf("expanding `identity`: %+v", err) + } + + // api will error if TypeNone is passed in + if expandedIdentity.Type != identity.TypeNone { + props.Identity = expandedIdentity + } + if id, ok := d.GetOk("base_policy_id"); ok { - props.FirewallPolicyPropertiesFormat.BasePolicy = &network.SubResource{ID: utils.String(id.(string))} + props.Properties.BasePolicy = &firewallpolicies.SubResource{Id: utils.String(id.(string))} } if v, ok := d.GetOk("sku"); ok { - props.FirewallPolicyPropertiesFormat.Sku = &network.FirewallPolicySku{ - Tier: network.FirewallPolicySkuTier(v.(string)), + props.Properties.Sku = &firewallpolicies.FirewallPolicySku{ + Tier: pointer.To(firewallpolicies.FirewallPolicySkuTier(v.(string))), } } if v, ok := d.GetOk("sql_redirect_allowed"); ok { - props.FirewallPolicyPropertiesFormat.SQL = &network.FirewallPolicySQL{ - AllowSQLRedirect: utils.Bool(v.(bool)), + props.Properties.Sql = &firewallpolicies.FirewallPolicySQL{ + AllowSqlRedirect: utils.Bool(v.(bool)), } } if v, ok := d.GetOk("private_ip_ranges"); ok { privateIPRanges := utils.ExpandStringSlice(v.([]interface{})) - props.FirewallPolicyPropertiesFormat.Snat = &network.FirewallPolicySNAT{ + props.Properties.Snat = &firewallpolicies.FirewallPolicySNAT{ PrivateRanges: privateIPRanges, } } if v, ok := d.GetOk("auto_learn_private_ranges_enabled"); ok { - if props.FirewallPolicyPropertiesFormat.Snat == nil { - props.FirewallPolicyPropertiesFormat.Snat = &network.FirewallPolicySNAT{} + if props.Properties.Snat == nil { + props.Properties.Snat = &firewallpolicies.FirewallPolicySNAT{} } if v.(bool) { - props.FirewallPolicyPropertiesFormat.Snat.AutoLearnPrivateRanges = network.AutoLearnPrivateRangesModeEnabled + props.Properties.Snat.AutoLearnPrivateRanges = pointer.To(firewallpolicies.AutoLearnPrivateRangesModeEnabled) } } - locks.ByName(id.Name, AzureFirewallPolicyResourceName) - defer locks.UnlockByName(id.Name, AzureFirewallPolicyResourceName) + locks.ByName(id.FirewallPolicyName, AzureFirewallPolicyResourceName) + defer locks.UnlockByName(id.FirewallPolicyName, AzureFirewallPolicyResourceName) - future, err := client.CreateOrUpdate(ctx, id.ResourceGroup, id.Name, props) - if err != nil { + if err := client.CreateOrUpdateThenPoll(ctx, id, props); err != nil { return fmt.Errorf("creating/updating %s: %+v", id, err) } - if err := future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for creating/updating %s: %+v", id, err) - } d.SetId(id.ID()) @@ -141,145 +142,143 @@ func resourceFirewallPolicyCreateUpdate(d *pluginsdk.ResourceData, meta interfac } func resourceFirewallPolicyRead(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Firewall.FirewallPolicyClient + client := meta.(*clients.Client).Firewall.Client.FirewallPolicies ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.FirewallPolicyID(d.Id()) + id, err := firewallpolicies.ParseFirewallPolicyID(d.Id()) if err != nil { return err } - resp, err := client.Get(ctx, id.ResourceGroup, id.Name, "") + resp, err := client.Get(ctx, *id, firewallpolicies.DefaultGetOperationOptions()) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - log.Printf("[DEBUG] Firewall Policy %q was not found in Resource Group %q - removing from state!", id.Name, id.ResourceGroup) + if response.WasNotFound(resp.HttpResponse) { + log.Printf("[DEBUG] %s was not found - removing from state!", id) d.SetId("") return nil } - return fmt.Errorf("retrieving Firewall Policy %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) + return fmt.Errorf("retrieving %s: %+v", id, err) } - d.Set("name", id.Name) - d.Set("resource_group_name", id.ResourceGroup) - d.Set("location", location.NormalizeNilable(resp.Location)) + d.Set("name", id.FirewallPolicyName) + d.Set("resource_group_name", id.ResourceGroupName) - if prop := resp.FirewallPolicyPropertiesFormat; prop != nil { - basePolicyID := "" - if resp.BasePolicy != nil && resp.BasePolicy.ID != nil { - basePolicyID = *resp.BasePolicy.ID - } - d.Set("base_policy_id", basePolicyID) + if model := resp.Model; model != nil { + d.Set("location", location.NormalizeNilable(model.Location)) - d.Set("threat_intelligence_mode", string(prop.ThreatIntelMode)) + if props := model.Properties; props != nil { + basePolicyID := "" + if props.BasePolicy != nil && props.BasePolicy.Id != nil { + basePolicyID = *props.BasePolicy.Id + } + d.Set("base_policy_id", basePolicyID) - if sku := prop.Sku; sku != nil { - d.Set("sku", string(sku.Tier)) - } + d.Set("threat_intelligence_mode", string(pointer.From(props.ThreatIntelMode))) - if err := d.Set("threat_intelligence_allowlist", flattenFirewallPolicyThreatIntelWhitelist(resp.ThreatIntelWhitelist)); err != nil { - return fmt.Errorf(`setting "threat_intelligence_allowlist": %+v`, err) - } + if sku := props.Sku; sku != nil { + d.Set("sku", string(pointer.From(sku.Tier))) + } - if err := d.Set("dns", flattenFirewallPolicyDNSSetting(prop.DNSSettings)); err != nil { - return fmt.Errorf(`setting "dns": %+v`, err) - } + if err := d.Set("threat_intelligence_allowlist", flattenFirewallPolicyThreatIntelWhitelist(props.ThreatIntelWhitelist)); err != nil { + return fmt.Errorf(`setting "threat_intelligence_allowlist": %+v`, err) + } - if err := d.Set("intrusion_detection", flattenFirewallPolicyIntrusionDetection(resp.IntrusionDetection)); err != nil { - return fmt.Errorf(`setting "intrusion_detection": %+v`, err) - } + if err := d.Set("dns", flattenFirewallPolicyDNSSetting(props.DnsSettings)); err != nil { + return fmt.Errorf(`setting "dns": %+v`, err) + } - if err := d.Set("tls_certificate", flattenFirewallPolicyTransportSecurity(prop.TransportSecurity)); err != nil { - return fmt.Errorf(`setting "tls_certificate": %+v`, err) - } + if err := d.Set("intrusion_detection", flattenFirewallPolicyIntrusionDetection(props.IntrusionDetection)); err != nil { + return fmt.Errorf(`setting "intrusion_detection": %+v`, err) + } - if err := d.Set("child_policies", flattenNetworkSubResourceID(prop.ChildPolicies)); err != nil { - return fmt.Errorf(`setting "child_policies": %+v`, err) - } + if err := d.Set("tls_certificate", flattenFirewallPolicyTransportSecurity(props.TransportSecurity)); err != nil { + return fmt.Errorf(`setting "tls_certificate": %+v`, err) + } - if err := d.Set("firewalls", flattenNetworkSubResourceID(prop.Firewalls)); err != nil { - return fmt.Errorf(`setting "firewalls": %+v`, err) - } + if err := d.Set("child_policies", flattenNetworkSubResourceID(props.ChildPolicies)); err != nil { + return fmt.Errorf(`setting "child_policies": %+v`, err) + } - if err := d.Set("rule_collection_groups", flattenNetworkSubResourceID(prop.RuleCollectionGroups)); err != nil { - return fmt.Errorf(`setting "rule_collection_groups": %+v`, err) - } + if err := d.Set("firewalls", flattenNetworkSubResourceID(props.Firewalls)); err != nil { + return fmt.Errorf(`setting "firewalls": %+v`, err) + } - var privateIPRanges []interface{} - var isAutoLearnPrivateRangeEnabled bool - if prop.Snat != nil { - privateIPRanges = utils.FlattenStringSlice(prop.Snat.PrivateRanges) - isAutoLearnPrivateRangeEnabled = prop.Snat.AutoLearnPrivateRanges == network.AutoLearnPrivateRangesModeEnabled - } - if err := d.Set("private_ip_ranges", privateIPRanges); err != nil { - return fmt.Errorf("setting `private_ip_ranges`: %+v", err) - } + if err := d.Set("rule_collection_groups", flattenNetworkSubResourceID(props.RuleCollectionGroups)); err != nil { + return fmt.Errorf(`setting "rule_collection_groups": %+v`, err) + } - if err := d.Set("auto_learn_private_ranges_enabled", isAutoLearnPrivateRangeEnabled); err != nil { - return fmt.Errorf("setting `auto_learn_private_ranges_enabled`: %+v", err) - } + var privateIPRanges []interface{} + var isAutoLearnPrivateRangeEnabled bool + if props.Snat != nil { + privateIPRanges = utils.FlattenStringSlice(props.Snat.PrivateRanges) + isAutoLearnPrivateRangeEnabled = pointer.From(props.Snat.AutoLearnPrivateRanges) == firewallpolicies.AutoLearnPrivateRangesModeEnabled + } + if err := d.Set("private_ip_ranges", privateIPRanges); err != nil { + return fmt.Errorf("setting `private_ip_ranges`: %+v", err) + } - if err := d.Set("insights", flattenFirewallPolicyInsights(prop.Insights)); err != nil { - return fmt.Errorf(`setting "insights": %+v`, err) - } + if err := d.Set("auto_learn_private_ranges_enabled", isAutoLearnPrivateRangeEnabled); err != nil { + return fmt.Errorf("setting `auto_learn_private_ranges_enabled`: %+v", err) + } - proxySettings := flattenFirewallPolicyExplicitProxy(prop.ExplicitProxy) - if err := d.Set("explicit_proxy", proxySettings); err != nil { - return fmt.Errorf("setting `explicit_proxy`: %+v", err) - } + if err := d.Set("insights", flattenFirewallPolicyInsights(props.Insights)); err != nil { + return fmt.Errorf(`setting "insights": %+v`, err) + } - if prop.SQL != nil && prop.SQL.AllowSQLRedirect != nil { - if err := d.Set("sql_redirect_allowed", prop.SQL.AllowSQLRedirect); err != nil { - return fmt.Errorf("setting `sql_redirect_allowed`: %+v", err) + proxySettings := flattenFirewallPolicyExplicitProxy(props.ExplicitProxy) + if err := d.Set("explicit_proxy", proxySettings); err != nil { + return fmt.Errorf("setting `explicit_proxy`: %+v", err) + } + + if props.Sql != nil && props.Sql.AllowSqlRedirect != nil { + if err := d.Set("sql_redirect_allowed", props.Sql.AllowSqlRedirect); err != nil { + return fmt.Errorf("setting `sql_redirect_allowed`: %+v", err) + } } } - } - flattenedIdentity, err := flattenFirewallPolicyIdentity(resp.Identity) - if err != nil { - return fmt.Errorf("flattening `identity`: %+v", err) - } - if err := d.Set("identity", flattenedIdentity); err != nil { - return fmt.Errorf("setting `identity`: %+v", err) + flattenedIdentity, err := identity.FlattenSystemAndUserAssignedMap(model.Identity) + if err != nil { + return fmt.Errorf("flattening `identity`: %+v", err) + } + if err := d.Set("identity", flattenedIdentity); err != nil { + return fmt.Errorf("setting `identity`: %+v", err) + } + + return tags.FlattenAndSet(d, model.Tags) } - return tags.FlattenAndSet(d, resp.Tags) + return nil } func resourceFirewallPolicyDelete(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Firewall.FirewallPolicyClient + client := meta.(*clients.Client).Firewall.Client.FirewallPolicies ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.FirewallPolicyID(d.Id()) + id, err := firewallpolicies.ParseFirewallPolicyID(d.Id()) if err != nil { return err } - locks.ByName(id.Name, AzureFirewallPolicyResourceName) - defer locks.UnlockByName(id.Name, AzureFirewallPolicyResourceName) + locks.ByName(id.FirewallPolicyName, AzureFirewallPolicyResourceName) + defer locks.UnlockByName(id.FirewallPolicyName, AzureFirewallPolicyResourceName) - future, err := client.Delete(ctx, id.ResourceGroup, id.Name) - if err != nil { - return fmt.Errorf("deleting Firewall Policy %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) + if err := client.DeleteThenPoll(ctx, *id); err != nil { + return fmt.Errorf("deleting %s: %+v", id, err) } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - if !response.WasNotFound(future.Response()) { - return fmt.Errorf("waiting for deleting Firewall Policy %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) - } - } - return nil } -func expandFirewallPolicyThreatIntelWhitelist(input []interface{}) *network.FirewallPolicyThreatIntelWhitelist { +func expandFirewallPolicyThreatIntelWhitelist(input []interface{}) *firewallpolicies.FirewallPolicyThreatIntelWhitelist { if len(input) == 0 || input[0] == nil { return nil } raw := input[0].(map[string]interface{}) - output := &network.FirewallPolicyThreatIntelWhitelist{ + output := &firewallpolicies.FirewallPolicyThreatIntelWhitelist{ IPAddresses: utils.ExpandStringSlice(raw["ip_addresses"].(*pluginsdk.Set).List()), Fqdns: utils.ExpandStringSlice(raw["fqdns"].(*pluginsdk.Set).List()), } @@ -287,13 +286,13 @@ func expandFirewallPolicyThreatIntelWhitelist(input []interface{}) *network.Fire return output } -func expandFirewallPolicyDNSSetting(input []interface{}) *network.DNSSettings { +func expandFirewallPolicyDNSSetting(input []interface{}) *firewallpolicies.DnsSettings { if len(input) == 0 || input[0] == nil { return nil } raw := input[0].(map[string]interface{}) - output := &network.DNSSettings{ + output := &firewallpolicies.DnsSettings{ Servers: utils.ExpandStringSlice(raw["servers"].([]interface{})), EnableProxy: utils.Bool(raw["proxy_enabled"].(bool)), } @@ -301,30 +300,30 @@ func expandFirewallPolicyDNSSetting(input []interface{}) *network.DNSSettings { return output } -func expandFirewallPolicyIntrusionDetection(input []interface{}) *network.FirewallPolicyIntrusionDetection { +func expandFirewallPolicyIntrusionDetection(input []interface{}) *firewallpolicies.FirewallPolicyIntrusionDetection { if len(input) == 0 || input[0] == nil { return nil } raw := input[0].(map[string]interface{}) - var signatureOverrides []network.FirewallPolicyIntrusionDetectionSignatureSpecification + var signatureOverrides []firewallpolicies.FirewallPolicyIntrusionDetectionSignatureSpecification for _, v := range raw["signature_overrides"].([]interface{}) { overrides := v.(map[string]interface{}) - signatureOverrides = append(signatureOverrides, network.FirewallPolicyIntrusionDetectionSignatureSpecification{ - ID: utils.String(overrides["id"].(string)), - Mode: network.FirewallPolicyIntrusionDetectionStateType(overrides["state"].(string)), + signatureOverrides = append(signatureOverrides, firewallpolicies.FirewallPolicyIntrusionDetectionSignatureSpecification{ + Id: utils.String(overrides["id"].(string)), + Mode: pointer.To(firewallpolicies.FirewallPolicyIntrusionDetectionStateType(overrides["state"].(string))), }) } - var trafficBypass []network.FirewallPolicyIntrusionDetectionBypassTrafficSpecifications + var trafficBypass []firewallpolicies.FirewallPolicyIntrusionDetectionBypassTrafficSpecifications for _, v := range raw["traffic_bypass"].([]interface{}) { bypass := v.(map[string]interface{}) - trafficBypass = append(trafficBypass, network.FirewallPolicyIntrusionDetectionBypassTrafficSpecifications{ + trafficBypass = append(trafficBypass, firewallpolicies.FirewallPolicyIntrusionDetectionBypassTrafficSpecifications{ Name: utils.String(bypass["name"].(string)), Description: utils.String(bypass["description"].(string)), - Protocol: network.FirewallPolicyIntrusionDetectionProtocol(bypass["protocol"].(string)), + Protocol: pointer.To(firewallpolicies.FirewallPolicyIntrusionDetectionProtocol(bypass["protocol"].(string))), SourceAddresses: utils.ExpandStringSlice(bypass["source_addresses"].(*pluginsdk.Set).List()), DestinationAddresses: utils.ExpandStringSlice(bypass["destination_addresses"].(*pluginsdk.Set).List()), DestinationPorts: utils.ExpandStringSlice(bypass["destination_ports"].(*pluginsdk.Set).List()), @@ -338,9 +337,9 @@ func expandFirewallPolicyIntrusionDetection(input []interface{}) *network.Firewa privateRanges = append(privateRanges, v.(string)) } - return &network.FirewallPolicyIntrusionDetection{ - Mode: network.FirewallPolicyIntrusionDetectionStateType(raw["mode"].(string)), - Configuration: &network.FirewallPolicyIntrusionDetectionConfiguration{ + return &firewallpolicies.FirewallPolicyIntrusionDetection{ + Mode: pointer.To(firewallpolicies.FirewallPolicyIntrusionDetectionStateType(raw["mode"].(string))), + Configuration: &firewallpolicies.FirewallPolicyIntrusionDetectionConfiguration{ SignatureOverrides: &signatureOverrides, PrivateRanges: &privateRanges, BypassTrafficSettings: &trafficBypass, @@ -348,64 +347,37 @@ func expandFirewallPolicyIntrusionDetection(input []interface{}) *network.Firewa } } -func expandFirewallPolicyTransportSecurity(input []interface{}) *network.FirewallPolicyTransportSecurity { +func expandFirewallPolicyTransportSecurity(input []interface{}) *firewallpolicies.FirewallPolicyTransportSecurity { if len(input) == 0 || input[0] == nil { return nil } raw := input[0].(map[string]interface{}) - return &network.FirewallPolicyTransportSecurity{ - CertificateAuthority: &network.FirewallPolicyCertificateAuthority{ - KeyVaultSecretID: utils.String(raw["key_vault_secret_id"].(string)), + return &firewallpolicies.FirewallPolicyTransportSecurity{ + CertificateAuthority: &firewallpolicies.FirewallPolicyCertificateAuthority{ + KeyVaultSecretId: utils.String(raw["key_vault_secret_id"].(string)), Name: utils.String(raw["name"].(string)), }, } } -func expandFirewallPolicyIdentity(input []interface{}) (*network.ManagedServiceIdentity, error) { - expanded, err := identity.ExpandUserAssignedMap(input) - if err != nil { - return nil, err - } - - if expanded.Type == identity.TypeNone { - return nil, nil - } - - out := network.ManagedServiceIdentity{ - PrincipalID: nil, - TenantID: nil, - Type: network.ResourceIdentityType(string(expanded.Type)), - UserAssignedIdentities: nil, - } - if expanded.Type == identity.TypeUserAssigned { - out.UserAssignedIdentities = make(map[string]*network.ManagedServiceIdentityUserAssignedIdentitiesValue) - for k := range expanded.IdentityIds { - out.UserAssignedIdentities[k] = &network.ManagedServiceIdentityUserAssignedIdentitiesValue{ - // intentionally empty - } - } - } - return &out, nil -} - -func expandFirewallPolicyInsights(input []interface{}) *network.FirewallPolicyInsights { +func expandFirewallPolicyInsights(input []interface{}) *firewallpolicies.FirewallPolicyInsights { if len(input) == 0 || input[0] == nil { return nil } raw := input[0].(map[string]interface{}) - output := &network.FirewallPolicyInsights{ + output := &firewallpolicies.FirewallPolicyInsights{ IsEnabled: utils.Bool(raw["enabled"].(bool)), - RetentionDays: utils.Int32(int32(raw["retention_in_days"].(int))), + RetentionDays: utils.Int64(int64(raw["retention_in_days"].(int))), LogAnalyticsResources: expandFirewallPolicyLogAnalyticsResources(raw["default_log_analytics_workspace_id"].(string), raw["log_analytics_workspace"].([]interface{})), } return output } -func expandFirewallPolicyExplicitProxy(input []interface{}) *network.ExplicitProxy { +func expandFirewallPolicyExplicitProxy(input []interface{}) *firewallpolicies.ExplicitProxy { if len(input) == 0 || input[0] == nil { return nil } @@ -415,11 +387,11 @@ func expandFirewallPolicyExplicitProxy(input []interface{}) *network.ExplicitPro return nil } - output := &network.ExplicitProxy{ + output := &firewallpolicies.ExplicitProxy{ EnableExplicitProxy: utils.Bool(raw["enabled"].(bool)), - HTTPPort: utils.Int32(int32(raw["http_port"].(int))), - HTTPSPort: utils.Int32(int32(raw["https_port"].(int))), - PacFilePort: utils.Int32(int32(raw["pac_file_port"].(int))), + HTTPPort: utils.Int64(int64(raw["http_port"].(int))), + HTTPSPort: utils.Int64(int64(raw["https_port"].(int))), + PacFilePort: utils.Int64(int64(raw["pac_file_port"].(int))), PacFile: utils.String(raw["pac_file"].(string)), } @@ -430,20 +402,20 @@ func expandFirewallPolicyExplicitProxy(input []interface{}) *network.ExplicitPro return output } -func expandFirewallPolicyLogAnalyticsResources(defaultWorkspaceId string, workspaces []interface{}) *network.FirewallPolicyLogAnalyticsResources { - output := &network.FirewallPolicyLogAnalyticsResources{ - DefaultWorkspaceID: &network.SubResource{ - ID: &defaultWorkspaceId, +func expandFirewallPolicyLogAnalyticsResources(defaultWorkspaceId string, workspaces []interface{}) *firewallpolicies.FirewallPolicyLogAnalyticsResources { + output := &firewallpolicies.FirewallPolicyLogAnalyticsResources{ + DefaultWorkspaceId: &firewallpolicies.SubResource{ + Id: &defaultWorkspaceId, }, } - var workspaceList []network.FirewallPolicyLogAnalyticsWorkspace + var workspaceList []firewallpolicies.FirewallPolicyLogAnalyticsWorkspace for _, workspace := range workspaces { workspace := workspace.(map[string]interface{}) - workspaceList = append(workspaceList, network.FirewallPolicyLogAnalyticsWorkspace{ + workspaceList = append(workspaceList, firewallpolicies.FirewallPolicyLogAnalyticsWorkspace{ Region: utils.String(location.Normalize(workspace["firewall_location"].(string))), - WorkspaceID: &network.SubResource{ - ID: utils.String(workspace["id"].(string)), + WorkspaceId: &firewallpolicies.SubResource{ + Id: utils.String(workspace["id"].(string)), }, }) } @@ -454,7 +426,7 @@ func expandFirewallPolicyLogAnalyticsResources(defaultWorkspaceId string, worksp return output } -func flattenFirewallPolicyThreatIntelWhitelist(input *network.FirewallPolicyThreatIntelWhitelist) []interface{} { +func flattenFirewallPolicyThreatIntelWhitelist(input *firewallpolicies.FirewallPolicyThreatIntelWhitelist) []interface{} { if input == nil { return []interface{}{} } @@ -467,7 +439,7 @@ func flattenFirewallPolicyThreatIntelWhitelist(input *network.FirewallPolicyThre } } -func flattenFirewallPolicyDNSSetting(input *network.DNSSettings) []interface{} { +func flattenFirewallPolicyDNSSetting(input *firewallpolicies.DnsSettings) []interface{} { if input == nil { return []interface{}{} } @@ -484,7 +456,7 @@ func flattenFirewallPolicyDNSSetting(input *network.DNSSettings) []interface{} { }} } -func flattenFirewallPolicyIntrusionDetection(input *network.FirewallPolicyIntrusionDetection) []interface{} { +func flattenFirewallPolicyIntrusionDetection(input *firewallpolicies.FirewallPolicyIntrusionDetection) []interface{} { if input == nil { return []interface{}{} } @@ -495,7 +467,7 @@ func flattenFirewallPolicyIntrusionDetection(input *network.FirewallPolicyIntrus if input.Configuration == nil { return []interface{}{ map[string]interface{}{ - "mode": string(input.Mode), + "mode": string(pointer.From(input.Mode)), "signature_overrides": signatureOverrides, "traffic_bypass": trafficBypass, }, @@ -505,12 +477,12 @@ func flattenFirewallPolicyIntrusionDetection(input *network.FirewallPolicyIntrus if overrides := input.Configuration.SignatureOverrides; overrides != nil { for _, override := range *overrides { id := "" - if override.ID != nil { - id = *override.ID + if override.Id != nil { + id = *override.Id } signatureOverrides = append(signatureOverrides, map[string]interface{}{ "id": id, - "state": string(override.Mode), + "state": string(pointer.From(override.Mode)), }) } } @@ -555,7 +527,7 @@ func flattenFirewallPolicyIntrusionDetection(input *network.FirewallPolicyIntrus trafficBypass = append(trafficBypass, map[string]interface{}{ "name": name, "description": description, - "protocol": string(bypass.Protocol), + "protocol": string(pointer.From(bypass.Protocol)), "source_addresses": sourceAddresses, "destination_addresses": destinationAddresses, "destination_ports": destinationPorts, @@ -571,7 +543,7 @@ func flattenFirewallPolicyIntrusionDetection(input *network.FirewallPolicyIntrus return []interface{}{ map[string]interface{}{ - "mode": string(input.Mode), + "mode": string(pointer.From(input.Mode)), "signature_overrides": signatureOverrides, "traffic_bypass": trafficBypass, "private_ranges": privateRanges, @@ -579,39 +551,20 @@ func flattenFirewallPolicyIntrusionDetection(input *network.FirewallPolicyIntrus } } -func flattenFirewallPolicyTransportSecurity(input *network.FirewallPolicyTransportSecurity) []interface{} { +func flattenFirewallPolicyTransportSecurity(input *firewallpolicies.FirewallPolicyTransportSecurity) []interface{} { if input == nil || input.CertificateAuthority == nil { return []interface{}{} } return []interface{}{ map[string]interface{}{ - "key_vault_secret_id": input.CertificateAuthority.KeyVaultSecretID, + "key_vault_secret_id": input.CertificateAuthority.KeyVaultSecretId, "name": input.CertificateAuthority.Name, }, } } -func flattenFirewallPolicyIdentity(input *network.ManagedServiceIdentity) (*[]interface{}, error) { - var transition *identity.UserAssignedMap - - if input != nil { - transition = &identity.UserAssignedMap{ - Type: identity.Type(string(input.Type)), - IdentityIds: make(map[string]identity.UserAssignedIdentityDetails), - } - for k, v := range input.UserAssignedIdentities { - transition.IdentityIds[k] = identity.UserAssignedIdentityDetails{ - ClientId: v.ClientID, - PrincipalId: v.PrincipalID, - } - } - } - - return identity.FlattenUserAssignedMap(transition) -} - -func flattenFirewallPolicyInsights(input *network.FirewallPolicyInsights) []interface{} { +func flattenFirewallPolicyInsights(input *firewallpolicies.FirewallPolicyInsights) []interface{} { if input == nil { return []interface{}{} } @@ -638,7 +591,7 @@ func flattenFirewallPolicyInsights(input *network.FirewallPolicyInsights) []inte } } -func flattenFirewallPolicyExplicitProxy(input *network.ExplicitProxy) (result []interface{}) { +func flattenFirewallPolicyExplicitProxy(input *firewallpolicies.ExplicitProxy) (result []interface{}) { if input == nil { return } @@ -653,14 +606,14 @@ func flattenFirewallPolicyExplicitProxy(input *network.ExplicitProxy) (result [] return []interface{}{output} } -func flattenFirewallPolicyLogAnalyticsResources(input *network.FirewallPolicyLogAnalyticsResources) (string, []interface{}) { +func flattenFirewallPolicyLogAnalyticsResources(input *firewallpolicies.FirewallPolicyLogAnalyticsResources) (string, []interface{}) { if input == nil { return "", []interface{}{} } var defaultLogAnalyticsWorkspaceId string - if input.DefaultWorkspaceID != nil && input.DefaultWorkspaceID.ID != nil { - defaultLogAnalyticsWorkspaceId = *input.DefaultWorkspaceID.ID + if input.DefaultWorkspaceId != nil && input.DefaultWorkspaceId.Id != nil { + defaultLogAnalyticsWorkspaceId = *input.DefaultWorkspaceId.Id } var workspaceList []interface{} @@ -669,8 +622,8 @@ func flattenFirewallPolicyLogAnalyticsResources(input *network.FirewallPolicyLog loc := location.NormalizeNilable(workspace.Region) var id string - if workspace.WorkspaceID != nil && workspace.WorkspaceID.ID != nil { - id = *workspace.WorkspaceID.ID + if workspace.WorkspaceId != nil && workspace.WorkspaceId.Id != nil { + id = *workspace.WorkspaceId.Id } workspaceList = append(workspaceList, map[string]interface{}{ @@ -700,9 +653,9 @@ func resourceFirewallPolicySchema() map[string]*pluginsdk.Schema { Computed: true, ForceNew: true, ValidateFunc: validation.StringInSlice([]string{ - string(network.FirewallPolicySkuTierPremium), - string(network.FirewallPolicySkuTierStandard), - string(network.FirewallPolicySkuTierBasic), + string(firewallpolicies.FirewallPolicySkuTierPremium), + string(firewallpolicies.FirewallPolicySkuTierStandard), + string(firewallpolicies.FirewallPolicySkuTierBasic), }, false), }, @@ -711,7 +664,7 @@ func resourceFirewallPolicySchema() map[string]*pluginsdk.Schema { "base_policy_id": { Type: pluginsdk.TypeString, Optional: true, - ValidateFunc: validate.FirewallPolicyID, + ValidateFunc: firewallpolicies.ValidateFirewallPolicyID, }, "dns": { @@ -741,11 +694,11 @@ func resourceFirewallPolicySchema() map[string]*pluginsdk.Schema { "threat_intelligence_mode": { Type: pluginsdk.TypeString, Optional: true, - Default: string(network.AzureFirewallThreatIntelModeAlert), + Default: string(firewallpolicies.AzureFirewallThreatIntelModeAlert), ValidateFunc: validation.StringInSlice([]string{ - string(network.AzureFirewallThreatIntelModeAlert), - string(network.AzureFirewallThreatIntelModeDeny), - string(network.AzureFirewallThreatIntelModeOff), + string(firewallpolicies.AzureFirewallThreatIntelModeAlert), + string(firewallpolicies.AzureFirewallThreatIntelModeDeny), + string(firewallpolicies.AzureFirewallThreatIntelModeOff), }, false), }, @@ -787,9 +740,9 @@ func resourceFirewallPolicySchema() map[string]*pluginsdk.Schema { "mode": { Type: pluginsdk.TypeString, ValidateFunc: validation.StringInSlice([]string{ - string(network.FirewallPolicyIntrusionDetectionStateTypeOff), - string(network.FirewallPolicyIntrusionDetectionStateTypeAlert), - string(network.FirewallPolicyIntrusionDetectionStateTypeDeny), + string(firewallpolicies.FirewallPolicyIntrusionDetectionStateTypeOff), + string(firewallpolicies.FirewallPolicyIntrusionDetectionStateTypeAlert), + string(firewallpolicies.FirewallPolicyIntrusionDetectionStateTypeDeny), }, false), Optional: true, }, @@ -801,9 +754,9 @@ func resourceFirewallPolicySchema() map[string]*pluginsdk.Schema { "state": { Type: pluginsdk.TypeString, ValidateFunc: validation.StringInSlice([]string{ - string(network.FirewallPolicyIntrusionDetectionStateTypeOff), - string(network.FirewallPolicyIntrusionDetectionStateTypeAlert), - string(network.FirewallPolicyIntrusionDetectionStateTypeDeny), + string(firewallpolicies.FirewallPolicyIntrusionDetectionStateTypeOff), + string(firewallpolicies.FirewallPolicyIntrusionDetectionStateTypeAlert), + string(firewallpolicies.FirewallPolicyIntrusionDetectionStateTypeDeny), }, false), Optional: true, }, @@ -840,10 +793,10 @@ func resourceFirewallPolicySchema() map[string]*pluginsdk.Schema { // protocol to be one of [ICMP ANY TCP UDP] but response may be "Any" DiffSuppressFunc: suppress.CaseDifference, ValidateFunc: validation.StringInSlice([]string{ - string(network.FirewallPolicyIntrusionDetectionProtocolICMP), - string(network.FirewallPolicyIntrusionDetectionProtocolANY), - string(network.FirewallPolicyIntrusionDetectionProtocolTCP), - string(network.FirewallPolicyIntrusionDetectionProtocolUDP), + string(firewallpolicies.FirewallPolicyIntrusionDetectionProtocolICMP), + string(firewallpolicies.FirewallPolicyIntrusionDetectionProtocolANY), + string(firewallpolicies.FirewallPolicyIntrusionDetectionProtocolTCP), + string(firewallpolicies.FirewallPolicyIntrusionDetectionProtocolUDP), }, true), }, "source_addresses": { @@ -888,7 +841,7 @@ func resourceFirewallPolicySchema() map[string]*pluginsdk.Schema { }, }, - "identity": commonschema.UserAssignedIdentityOptional(), + "identity": commonschema.SystemAssignedUserAssignedIdentityOptional(), "tls_certificate": { Type: pluginsdk.TypeList, @@ -1032,6 +985,6 @@ func resourceFirewallPolicySchema() map[string]*pluginsdk.Schema { Optional: true, }, - "tags": tags.Schema(), + "tags": commonschema.Tags(), } } diff --git a/internal/services/firewall/firewall_policy_resource_test.go b/internal/services/firewall/firewall_policy_resource_test.go index ec0a4acc7a2a..48fe15e38099 100644 --- a/internal/services/firewall/firewall_policy_resource_test.go +++ b/internal/services/firewall/firewall_policy_resource_test.go @@ -8,10 +8,10 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/network/2023-04-01/firewallpolicies" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/firewall/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -194,17 +194,17 @@ func TestAccFirewallPolicy_insights(t *testing.T) { } func (FirewallPolicyResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.FirewallPolicyID(state.ID) + id, err := firewallpolicies.ParseFirewallPolicyID(state.ID) if err != nil { return nil, err } - resp, err := clients.Firewall.FirewallPolicyClient.Get(ctx, id.ResourceGroup, id.Name, "") + resp, err := clients.Firewall.Client.FirewallPolicies.Get(ctx, *id, firewallpolicies.DefaultGetOperationOptions()) if err != nil { return nil, fmt.Errorf("retrieving %s: %v", id.String(), err) } - return utils.Bool(resp.FirewallPolicyPropertiesFormat != nil), nil + return utils.Bool(resp.Model != nil), nil } func (FirewallPolicyResource) basic(data acceptance.TestData) string { diff --git a/internal/services/firewall/firewall_policy_rule_collection_group_resource.go b/internal/services/firewall/firewall_policy_rule_collection_group_resource.go index 1c17b1d10915..3bc95544e0d8 100644 --- a/internal/services/firewall/firewall_policy_rule_collection_group_resource.go +++ b/internal/services/firewall/firewall_policy_rule_collection_group_resource.go @@ -7,20 +7,21 @@ import ( "fmt" "log" "strconv" + "strings" "time" "github.com/hashicorp/go-azure-helpers/lang/pointer" "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/network/2023-04-01/firewallpolicies" + "github.com/hashicorp/go-azure-sdk/resource-manager/network/2023-04-01/firewallpolicyrulecollectiongroups" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/locks" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/firewall/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/firewall/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/kermit/sdk/network/2022-07-01/network" ) func resourceFirewallPolicyRuleCollectionGroup() *pluginsdk.Resource { @@ -31,7 +32,7 @@ func resourceFirewallPolicyRuleCollectionGroup() *pluginsdk.Resource { Delete: resourceFirewallPolicyRuleCollectionGroupDelete, Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.FirewallPolicyRuleCollectionGroupID(id) + _, err := firewallpolicyrulecollectiongroups.ParseRuleCollectionGroupID(id) return err }), @@ -54,7 +55,7 @@ func resourceFirewallPolicyRuleCollectionGroup() *pluginsdk.Resource { Type: pluginsdk.TypeString, Required: true, ForceNew: true, - ValidateFunc: validate.FirewallPolicyID, + ValidateFunc: firewallpolicies.ValidateFirewallPolicyID, }, "priority": { @@ -83,8 +84,8 @@ func resourceFirewallPolicyRuleCollectionGroup() *pluginsdk.Resource { Type: pluginsdk.TypeString, Required: true, ValidateFunc: validation.StringInSlice([]string{ - string(network.FirewallPolicyFilterRuleCollectionActionTypeAllow), - string(network.FirewallPolicyFilterRuleCollectionActionTypeDeny), + string(firewallpolicyrulecollectiongroups.FirewallPolicyFilterRuleCollectionActionTypeAllow), + string(firewallpolicyrulecollectiongroups.FirewallPolicyFilterRuleCollectionActionTypeDeny), }, false), }, "rule": { @@ -112,8 +113,8 @@ func resourceFirewallPolicyRuleCollectionGroup() *pluginsdk.Resource { Type: pluginsdk.TypeString, Required: true, ValidateFunc: validation.StringInSlice([]string{ - string(network.FirewallPolicyRuleApplicationProtocolTypeHTTP), - string(network.FirewallPolicyRuleApplicationProtocolTypeHTTPS), + string(firewallpolicyrulecollectiongroups.FirewallPolicyRuleApplicationProtocolTypeHTTP), + string(firewallpolicyrulecollectiongroups.FirewallPolicyRuleApplicationProtocolTypeHTTPS), "Mssql", }, false), }, @@ -222,8 +223,8 @@ func resourceFirewallPolicyRuleCollectionGroup() *pluginsdk.Resource { Type: pluginsdk.TypeString, Required: true, ValidateFunc: validation.StringInSlice([]string{ - string(network.FirewallPolicyFilterRuleCollectionActionTypeAllow), - string(network.FirewallPolicyFilterRuleCollectionActionTypeDeny), + string(firewallpolicyrulecollectiongroups.FirewallPolicyFilterRuleCollectionActionTypeAllow), + string(firewallpolicyrulecollectiongroups.FirewallPolicyFilterRuleCollectionActionTypeDeny), }, false), }, "rule": { @@ -248,10 +249,10 @@ func resourceFirewallPolicyRuleCollectionGroup() *pluginsdk.Resource { Elem: &pluginsdk.Schema{ Type: pluginsdk.TypeString, ValidateFunc: validation.StringInSlice([]string{ - string(network.FirewallPolicyRuleNetworkProtocolAny), - string(network.FirewallPolicyRuleNetworkProtocolTCP), - string(network.FirewallPolicyRuleNetworkProtocolUDP), - string(network.FirewallPolicyRuleNetworkProtocolICMP), + string(firewallpolicyrulecollectiongroups.FirewallPolicyRuleNetworkProtocolAny), + string(firewallpolicyrulecollectiongroups.FirewallPolicyRuleNetworkProtocolTCP), + string(firewallpolicyrulecollectiongroups.FirewallPolicyRuleNetworkProtocolUDP), + string(firewallpolicyrulecollectiongroups.FirewallPolicyRuleNetworkProtocolICMP), }, false), }, }, @@ -339,7 +340,7 @@ func resourceFirewallPolicyRuleCollectionGroup() *pluginsdk.Resource { Type: pluginsdk.TypeString, Required: true, ValidateFunc: validation.StringInSlice([]string{ - // Hardcode to using `Dnat` instead of the one defined in Swagger (i.e. network.DNAT) because of: https://github.com/Azure/azure-rest-api-specs/issues/9986 + // Hardcode to using `Dnat` instead of the one defined in Swagger (i.e. firewallpolicyrulecollectiongroups.DNAT) because of: https://github.com/Azure/azure-rest-api-specs/issues/9986 // Setting `StateFunc: state.IgnoreCase` will cause other issues, as tracked by: https://github.com/hashicorp/terraform-plugin-sdk/issues/485 "Dnat", }, false), @@ -366,8 +367,8 @@ func resourceFirewallPolicyRuleCollectionGroup() *pluginsdk.Resource { Elem: &pluginsdk.Schema{ Type: pluginsdk.TypeString, ValidateFunc: validation.StringInSlice([]string{ - string(network.FirewallPolicyRuleNetworkProtocolTCP), - string(network.FirewallPolicyRuleNetworkProtocolUDP), + string(firewallpolicyrulecollectiongroups.FirewallPolicyRuleNetworkProtocolTCP), + string(firewallpolicyrulecollectiongroups.FirewallPolicyRuleNetworkProtocolUDP), }, false), }, }, @@ -436,38 +437,39 @@ func resourceFirewallPolicyRuleCollectionGroup() *pluginsdk.Resource { } func resourceFirewallPolicyRuleCollectionGroupCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Firewall.FirewallPolicyRuleGroupClient + client := meta.(*clients.Client).Firewall.Client.FirewallPolicyRuleCollectionGroups ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - name := d.Get("name").(string) - policyId, err := parse.FirewallPolicyID(d.Get("firewall_policy_id").(string)) + policyId, err := firewallpolicies.ParseFirewallPolicyID(d.Get("firewall_policy_id").(string)) if err != nil { return err } + id := firewallpolicyrulecollectiongroups.NewRuleCollectionGroupID(policyId.SubscriptionId, policyId.ResourceGroupName, policyId.FirewallPolicyName, d.Get("name").(string)) + if d.IsNewResource() { - resp, err := client.Get(ctx, policyId.ResourceGroup, policyId.Name, name) + resp, err := client.Get(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(resp.Response) { - return fmt.Errorf("checking for existing Firewall Policy Rule Collection Group %q (Resource Group %q / Policy %q): %+v", name, policyId.ResourceGroup, policyId.Name, err) + if !response.WasNotFound(resp.HttpResponse) { + return fmt.Errorf("checking for existing %s: %+v", id, err) } } - if resp.ID != nil && *resp.ID != "" { - return tf.ImportAsExistsError("azurerm_firewall_policy_rule_collection_group", *resp.ID) + if resp.Model != nil { + return tf.ImportAsExistsError("azurerm_firewall_policy_rule_collection_group", id.ID()) } } - locks.ByName(policyId.Name, AzureFirewallPolicyResourceName) - defer locks.UnlockByName(policyId.Name, AzureFirewallPolicyResourceName) + locks.ByName(policyId.FirewallPolicyName, AzureFirewallPolicyResourceName) + defer locks.UnlockByName(policyId.FirewallPolicyName, AzureFirewallPolicyResourceName) - param := network.FirewallPolicyRuleCollectionGroup{ - FirewallPolicyRuleCollectionGroupProperties: &network.FirewallPolicyRuleCollectionGroupProperties{ - Priority: utils.Int32(int32(d.Get("priority").(int))), + param := firewallpolicyrulecollectiongroups.FirewallPolicyRuleCollectionGroup{ + Properties: &firewallpolicyrulecollectiongroups.FirewallPolicyRuleCollectionGroupProperties{ + Priority: utils.Int64(int64(d.Get("priority").(int))), }, } - var rulesCollections []network.BasicFirewallPolicyRuleCollection + var rulesCollections []firewallpolicyrulecollectiongroups.FirewallPolicyRuleCollection rulesCollections = append(rulesCollections, expandFirewallPolicyRuleCollectionApplication(d.Get("application_rule_collection").([]interface{}))...) rulesCollections = append(rulesCollections, expandFirewallPolicyRuleCollectionNetwork(d.Get("network_rule_collection").([]interface{}))...) @@ -477,27 +479,12 @@ func resourceFirewallPolicyRuleCollectionGroupCreateUpdate(d *pluginsdk.Resource } rulesCollections = append(rulesCollections, natRules...) - param.FirewallPolicyRuleCollectionGroupProperties.RuleCollections = &rulesCollections + param.Properties.RuleCollections = &rulesCollections - future, err := client.CreateOrUpdate(ctx, policyId.ResourceGroup, policyId.Name, name, param) - if err != nil { - return fmt.Errorf("creating Firewall Policy Rule Collection Group %q (Resource Group %q / Policy: %q): %+v", name, policyId.ResourceGroup, policyId.Name, err) - } - if err := future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting Firewall Policy Rule Collection Group %q (Resource Group %q / Policy: %q): %+v", name, policyId.ResourceGroup, policyId.Name, err) + if err = client.CreateOrUpdateThenPoll(ctx, id, param); err != nil { + return fmt.Errorf("creating %s: %+v", id, err) } - resp, err := client.Get(ctx, policyId.ResourceGroup, policyId.Name, name) - if err != nil { - return fmt.Errorf("retrieving Firewall Policy Rule Collection Group %q (Resource Group %q / Policy: %q): %+v", name, policyId.ResourceGroup, policyId.Name, err) - } - if resp.ID == nil || *resp.ID == "" { - return fmt.Errorf("empty or nil ID returned for Firewall Policy Rule Collection Group %q (Resource Group %q / Policy: %q) ID", name, policyId.ResourceGroup, policyId.Name) - } - id, err := parse.FirewallPolicyRuleCollectionGroupID(*resp.ID) - if err != nil { - return err - } d.SetId(id.ID()) return resourceFirewallPolicyRuleCollectionGroupRead(d, meta) @@ -505,54 +492,59 @@ func resourceFirewallPolicyRuleCollectionGroupCreateUpdate(d *pluginsdk.Resource func resourceFirewallPolicyRuleCollectionGroupRead(d *pluginsdk.ResourceData, meta interface{}) error { subscriptionId := meta.(*clients.Client).Account.SubscriptionId - client := meta.(*clients.Client).Firewall.FirewallPolicyRuleGroupClient + client := meta.(*clients.Client).Firewall.Client.FirewallPolicyRuleCollectionGroups ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.FirewallPolicyRuleCollectionGroupID(d.Id()) + id, err := firewallpolicyrulecollectiongroups.ParseRuleCollectionGroupID(d.Id()) if err != nil { return err } - resp, err := client.Get(ctx, id.ResourceGroup, id.FirewallPolicyName, id.RuleCollectionGroupName) + resp, err := client.Get(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - log.Printf("[DEBUG] Firewall Policy Rule Collection Group %q was not found in Resource Group %q - removing from state!", id.RuleCollectionGroupName, id.ResourceGroup) + if response.WasNotFound(resp.HttpResponse) { + log.Printf("[DEBUG] %s was not found- removing from state!", id) d.SetId("") return nil } - return fmt.Errorf("retrieving Firewall Policy Rule Collection Group %q (Resource Group %q / Policy: %q): %+v", id.RuleCollectionGroupName, id.ResourceGroup, id.FirewallPolicyName, err) + return fmt.Errorf("retrieving %s: %+v", id, err) } - d.Set("name", resp.Name) - d.Set("priority", resp.Priority) - d.Set("firewall_policy_id", parse.NewFirewallPolicyID(subscriptionId, id.ResourceGroup, id.FirewallPolicyName).ID()) + d.Set("name", id.RuleCollectionGroupName) + d.Set("firewall_policy_id", firewallpolicies.NewFirewallPolicyID(subscriptionId, id.ResourceGroupName, id.FirewallPolicyName).ID()) - applicationRuleCollections, networkRuleCollections, natRuleCollections, err := flattenFirewallPolicyRuleCollection(resp.RuleCollections) - if err != nil { - return fmt.Errorf("flattening Firewall Policy Rule Collections: %+v", err) - } + if model := resp.Model; model != nil { + if props := model.Properties; props != nil { + d.Set("priority", props.Priority) - if err := d.Set("application_rule_collection", applicationRuleCollections); err != nil { - return fmt.Errorf("setting `application_rule_collection`: %+v", err) - } - if err := d.Set("network_rule_collection", networkRuleCollections); err != nil { - return fmt.Errorf("setting `network_rule_collection`: %+v", err) - } - if err := d.Set("nat_rule_collection", natRuleCollections); err != nil { - return fmt.Errorf("setting `nat_rule_collection`: %+v", err) + applicationRuleCollections, networkRuleCollections, natRuleCollections, err := flattenFirewallPolicyRuleCollection(props.RuleCollections) + if err != nil { + return fmt.Errorf("flattening Firewall Policy Rule Collections: %+v", err) + } + + if err := d.Set("application_rule_collection", applicationRuleCollections); err != nil { + return fmt.Errorf("setting `application_rule_collection`: %+v", err) + } + if err := d.Set("network_rule_collection", networkRuleCollections); err != nil { + return fmt.Errorf("setting `network_rule_collection`: %+v", err) + } + if err := d.Set("nat_rule_collection", natRuleCollections); err != nil { + return fmt.Errorf("setting `nat_rule_collection`: %+v", err) + } + } } return nil } func resourceFirewallPolicyRuleCollectionGroupDelete(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Firewall.FirewallPolicyRuleGroupClient + client := meta.(*clients.Client).Firewall.Client.FirewallPolicyRuleCollectionGroups ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.FirewallPolicyRuleCollectionGroupID(d.Id()) + id, err := firewallpolicyrulecollectiongroups.ParseRuleCollectionGroupID(d.Id()) if err != nil { return err } @@ -560,41 +552,33 @@ func resourceFirewallPolicyRuleCollectionGroupDelete(d *pluginsdk.ResourceData, locks.ByName(id.FirewallPolicyName, AzureFirewallPolicyResourceName) defer locks.UnlockByName(id.FirewallPolicyName, AzureFirewallPolicyResourceName) - future, err := client.Delete(ctx, id.ResourceGroup, id.FirewallPolicyName, id.RuleCollectionGroupName) - if err != nil { - return fmt.Errorf("deleting Firewall Policy Rule Collection Group %q (Resource Group %q / Policy: %q): %+v", id.RuleCollectionGroupName, id.ResourceGroup, id.FirewallPolicyName, err) - } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - if !response.WasNotFound(future.Response()) { - return fmt.Errorf("waiting for deleting %q (Resource Group %q / Policy: %q): %+v", id.RuleCollectionGroupName, id.ResourceGroup, id.FirewallPolicyName, err) - } + if err = client.DeleteThenPoll(ctx, *id); err != nil { + return fmt.Errorf("deleting %s: %+v", id, err) } - return nil } -func expandFirewallPolicyRuleCollectionApplication(input []interface{}) []network.BasicFirewallPolicyRuleCollection { +func expandFirewallPolicyRuleCollectionApplication(input []interface{}) []firewallpolicyrulecollectiongroups.FirewallPolicyRuleCollection { return expandFirewallPolicyFilterRuleCollection(input, expandFirewallPolicyRuleApplication) } -func expandFirewallPolicyRuleCollectionNetwork(input []interface{}) []network.BasicFirewallPolicyRuleCollection { +func expandFirewallPolicyRuleCollectionNetwork(input []interface{}) []firewallpolicyrulecollectiongroups.FirewallPolicyRuleCollection { return expandFirewallPolicyFilterRuleCollection(input, expandFirewallPolicyRuleNetwork) } -func expandFirewallPolicyRuleCollectionNat(input []interface{}) ([]network.BasicFirewallPolicyRuleCollection, error) { - result := make([]network.BasicFirewallPolicyRuleCollection, 0) +func expandFirewallPolicyRuleCollectionNat(input []interface{}) ([]firewallpolicyrulecollectiongroups.FirewallPolicyRuleCollection, error) { + result := make([]firewallpolicyrulecollectiongroups.FirewallPolicyRuleCollection, 0) for _, e := range input { rule := e.(map[string]interface{}) rules, err := expandFirewallPolicyRuleNat(rule["rule"].([]interface{})) if err != nil { return nil, err } - output := &network.FirewallPolicyNatRuleCollection{ - RuleCollectionType: network.RuleCollectionTypeFirewallPolicyNatRuleCollection, - Name: utils.String(rule["name"].(string)), - Priority: utils.Int32(int32(rule["priority"].(int))), - Action: &network.FirewallPolicyNatRuleCollectionAction{ - Type: network.FirewallPolicyNatRuleCollectionActionType(rule["action"].(string)), + output := &firewallpolicyrulecollectiongroups.FirewallPolicyNatRuleCollection{ + Name: utils.String(rule["name"].(string)), + Priority: utils.Int64(int64(rule["priority"].(int))), + Action: &firewallpolicyrulecollectiongroups.FirewallPolicyNatRuleCollectionAction{ + Type: pointer.To(firewallpolicyrulecollectiongroups.FirewallPolicyNatRuleCollectionActionType(rule["action"].(string))), }, Rules: rules, } @@ -603,40 +587,38 @@ func expandFirewallPolicyRuleCollectionNat(input []interface{}) ([]network.Basic return result, nil } -func expandFirewallPolicyFilterRuleCollection(input []interface{}, f func(input []interface{}) *[]network.BasicFirewallPolicyRule) []network.BasicFirewallPolicyRuleCollection { - result := make([]network.BasicFirewallPolicyRuleCollection, 0) +func expandFirewallPolicyFilterRuleCollection(input []interface{}, f func(input []interface{}) *[]firewallpolicyrulecollectiongroups.FirewallPolicyRule) []firewallpolicyrulecollectiongroups.FirewallPolicyRuleCollection { + result := make([]firewallpolicyrulecollectiongroups.FirewallPolicyRuleCollection, 0) for _, e := range input { rule := e.(map[string]interface{}) - output := &network.FirewallPolicyFilterRuleCollection{ - Action: &network.FirewallPolicyFilterRuleCollectionAction{ - Type: network.FirewallPolicyFilterRuleCollectionActionType(rule["action"].(string)), + output := &firewallpolicyrulecollectiongroups.FirewallPolicyFilterRuleCollection{ + Action: &firewallpolicyrulecollectiongroups.FirewallPolicyFilterRuleCollectionAction{ + Type: pointer.To(firewallpolicyrulecollectiongroups.FirewallPolicyFilterRuleCollectionActionType(rule["action"].(string))), }, - Name: utils.String(rule["name"].(string)), - Priority: utils.Int32(int32(rule["priority"].(int))), - RuleCollectionType: network.RuleCollectionTypeFirewallPolicyFilterRuleCollection, - Rules: f(rule["rule"].([]interface{})), + Name: utils.String(rule["name"].(string)), + Priority: utils.Int64(int64(rule["priority"].(int))), + Rules: f(rule["rule"].([]interface{})), } result = append(result, output) } return result } -func expandFirewallPolicyRuleApplication(input []interface{}) *[]network.BasicFirewallPolicyRule { - result := make([]network.BasicFirewallPolicyRule, 0) +func expandFirewallPolicyRuleApplication(input []interface{}) *[]firewallpolicyrulecollectiongroups.FirewallPolicyRule { + result := make([]firewallpolicyrulecollectiongroups.FirewallPolicyRule, 0) for _, e := range input { condition := e.(map[string]interface{}) - var protocols []network.FirewallPolicyRuleApplicationProtocol + var protocols []firewallpolicyrulecollectiongroups.FirewallPolicyRuleApplicationProtocol for _, p := range condition["protocols"].([]interface{}) { proto := p.(map[string]interface{}) - protocols = append(protocols, network.FirewallPolicyRuleApplicationProtocol{ - ProtocolType: network.FirewallPolicyRuleApplicationProtocolType(proto["type"].(string)), - Port: utils.Int32(int32(proto["port"].(int))), + protocols = append(protocols, firewallpolicyrulecollectiongroups.FirewallPolicyRuleApplicationProtocol{ + ProtocolType: pointer.To(firewallpolicyrulecollectiongroups.FirewallPolicyRuleApplicationProtocolType(proto["type"].(string))), + Port: utils.Int64(int64(proto["port"].(int))), }) } - output := &network.ApplicationRule{ + output := &firewallpolicyrulecollectiongroups.ApplicationRule{ Name: utils.String(condition["name"].(string)), Description: utils.String(condition["description"].(string)), - RuleType: network.RuleTypeApplicationRule, Protocols: &protocols, SourceAddresses: utils.ExpandStringSlice(condition["source_addresses"].([]interface{})), SourceIPGroups: utils.ExpandStringSlice(condition["source_ip_groups"].([]interface{})), @@ -652,17 +634,16 @@ func expandFirewallPolicyRuleApplication(input []interface{}) *[]network.BasicFi return &result } -func expandFirewallPolicyRuleNetwork(input []interface{}) *[]network.BasicFirewallPolicyRule { - result := make([]network.BasicFirewallPolicyRule, 0) +func expandFirewallPolicyRuleNetwork(input []interface{}) *[]firewallpolicyrulecollectiongroups.FirewallPolicyRule { + result := make([]firewallpolicyrulecollectiongroups.FirewallPolicyRule, 0) for _, e := range input { condition := e.(map[string]interface{}) - var protocols []network.FirewallPolicyRuleNetworkProtocol + var protocols []firewallpolicyrulecollectiongroups.FirewallPolicyRuleNetworkProtocol for _, p := range condition["protocols"].([]interface{}) { - protocols = append(protocols, network.FirewallPolicyRuleNetworkProtocol(p.(string))) + protocols = append(protocols, firewallpolicyrulecollectiongroups.FirewallPolicyRuleNetworkProtocol(p.(string))) } - output := &network.Rule{ + output := &firewallpolicyrulecollectiongroups.NetworkRule{ Name: utils.String(condition["name"].(string)), - RuleType: network.RuleTypeNetworkRule, IPProtocols: &protocols, SourceAddresses: utils.ExpandStringSlice(condition["source_addresses"].([]interface{})), SourceIPGroups: utils.ExpandStringSlice(condition["source_ip_groups"].([]interface{})), @@ -677,13 +658,13 @@ func expandFirewallPolicyRuleNetwork(input []interface{}) *[]network.BasicFirewa return &result } -func expandFirewallPolicyRuleNat(input []interface{}) (*[]network.BasicFirewallPolicyRule, error) { - result := make([]network.BasicFirewallPolicyRule, 0) +func expandFirewallPolicyRuleNat(input []interface{}) (*[]firewallpolicyrulecollectiongroups.FirewallPolicyRule, error) { + result := make([]firewallpolicyrulecollectiongroups.FirewallPolicyRule, 0) for _, e := range input { condition := e.(map[string]interface{}) - var protocols []network.FirewallPolicyRuleNetworkProtocol + var protocols []firewallpolicyrulecollectiongroups.FirewallPolicyRuleNetworkProtocol for _, p := range condition["protocols"].([]interface{}) { - protocols = append(protocols, network.FirewallPolicyRuleNetworkProtocol(p.(string))) + protocols = append(protocols, firewallpolicyrulecollectiongroups.FirewallPolicyRuleNetworkProtocol(p.(string))) } destinationAddresses := []string{condition["destination_address"].(string)} @@ -694,9 +675,8 @@ func expandFirewallPolicyRuleNat(input []interface{}) (*[]network.BasicFirewallP if condition["translated_address"].(string) == "" && condition["translated_fqdn"].(string) == "" { return nil, fmt.Errorf("should specify either `translated_address` or `translated_fqdn` in rule %s", condition["name"].(string)) } - output := &network.NatRule{ + output := &firewallpolicyrulecollectiongroups.NatRule{ Name: utils.String(condition["name"].(string)), - RuleType: network.RuleTypeNatRule, IPProtocols: &protocols, SourceAddresses: utils.ExpandStringSlice(condition["source_addresses"].([]interface{})), SourceIPGroups: utils.ExpandStringSlice(condition["source_ip_groups"].([]interface{})), @@ -716,7 +696,7 @@ func expandFirewallPolicyRuleNat(input []interface{}) (*[]network.BasicFirewallP return &result, nil } -func flattenFirewallPolicyRuleCollection(input *[]network.BasicFirewallPolicyRuleCollection) ([]interface{}, []interface{}, []interface{}, error) { +func flattenFirewallPolicyRuleCollection(input *[]firewallpolicyrulecollectiongroups.FirewallPolicyRuleCollection) ([]interface{}, []interface{}, []interface{}, error) { var ( applicationRuleCollection = []interface{}{} networkRuleCollection = []interface{}{} @@ -730,19 +710,19 @@ func flattenFirewallPolicyRuleCollection(input *[]network.BasicFirewallPolicyRul var result map[string]interface{} switch rule := e.(type) { - case network.FirewallPolicyFilterRuleCollection: + case firewallpolicyrulecollectiongroups.FirewallPolicyFilterRuleCollection: var name string if rule.Name != nil { name = *rule.Name } - var priority int32 + var priority int64 if rule.Priority != nil { priority = *rule.Priority } var action string if rule.Action != nil { - action = string(rule.Action.Type) + action = string(pointer.From(rule.Action.Type)) } result = map[string]interface{}{ @@ -757,7 +737,7 @@ func flattenFirewallPolicyRuleCollection(input *[]network.BasicFirewallPolicyRul // Determine the rule type based on the first rule's type switch (*rule.Rules)[0].(type) { - case network.ApplicationRule: + case firewallpolicyrulecollectiongroups.ApplicationRule: appRules, err := flattenFirewallPolicyRuleApplication(rule.Rules) if err != nil { return nil, nil, nil, err @@ -766,7 +746,7 @@ func flattenFirewallPolicyRuleCollection(input *[]network.BasicFirewallPolicyRul applicationRuleCollection = append(applicationRuleCollection, result) - case network.Rule: + case firewallpolicyrulecollectiongroups.FirewallPolicyRule: networkRules, err := flattenFirewallPolicyRuleNetwork(rule.Rules) if err != nil { return nil, nil, nil, err @@ -778,19 +758,25 @@ func flattenFirewallPolicyRuleCollection(input *[]network.BasicFirewallPolicyRul default: return nil, nil, nil, fmt.Errorf("unknown rule condition type %+v", (*rule.Rules)[0]) } - case network.FirewallPolicyNatRuleCollection: + case firewallpolicyrulecollectiongroups.FirewallPolicyNatRuleCollection: var name string if rule.Name != nil { name = *rule.Name } - var priority int32 + var priority int64 if rule.Priority != nil { priority = *rule.Priority } var action string if rule.Action != nil { - action = string(rule.Action.Type) + // todo 4.0 change this from DNAT to Dnat + // doing this because we hardcode Dnat for https://github.com/Azure/azure-rest-api-specs/issues/9986 + if strings.EqualFold(string(pointer.From(rule.Action.Type)), "Dnat") { + action = "Dnat" + } else { + action = string(pointer.From(rule.Action.Type)) + } } rules, err := flattenFirewallPolicyRuleNat(rule.Rules) @@ -813,13 +799,13 @@ func flattenFirewallPolicyRuleCollection(input *[]network.BasicFirewallPolicyRul return applicationRuleCollection, networkRuleCollection, natRuleCollection, nil } -func flattenFirewallPolicyRuleApplication(input *[]network.BasicFirewallPolicyRule) ([]interface{}, error) { +func flattenFirewallPolicyRuleApplication(input *[]firewallpolicyrulecollectiongroups.FirewallPolicyRule) ([]interface{}, error) { if input == nil { return []interface{}{}, nil } output := make([]interface{}, 0) for _, e := range *input { - rule, ok := e.(network.ApplicationRule) + rule, ok := e.(firewallpolicyrulecollectiongroups.ApplicationRule) if !ok { return nil, fmt.Errorf("unexpected non-application rule: %+v", e) } @@ -847,7 +833,7 @@ func flattenFirewallPolicyRuleApplication(input *[]network.BasicFirewallPolicyRu port = int(*protocol.Port) } protocols = append(protocols, map[string]interface{}{ - "type": string(protocol.ProtocolType), + "type": string(pointer.From(protocol.ProtocolType)), "port": port, }) } @@ -871,13 +857,13 @@ func flattenFirewallPolicyRuleApplication(input *[]network.BasicFirewallPolicyRu return output, nil } -func flattenFirewallPolicyRuleNetwork(input *[]network.BasicFirewallPolicyRule) ([]interface{}, error) { +func flattenFirewallPolicyRuleNetwork(input *[]firewallpolicyrulecollectiongroups.FirewallPolicyRule) ([]interface{}, error) { if input == nil { return []interface{}{}, nil } output := make([]interface{}, 0) for _, e := range *input { - rule, ok := e.(network.Rule) + rule, ok := e.(firewallpolicyrulecollectiongroups.NetworkRule) if !ok { return nil, fmt.Errorf("unexpected non-network rule: %+v", e) } @@ -909,13 +895,13 @@ func flattenFirewallPolicyRuleNetwork(input *[]network.BasicFirewallPolicyRule) return output, nil } -func flattenFirewallPolicyRuleNat(input *[]network.BasicFirewallPolicyRule) ([]interface{}, error) { +func flattenFirewallPolicyRuleNat(input *[]firewallpolicyrulecollectiongroups.FirewallPolicyRule) ([]interface{}, error) { if input == nil { return []interface{}{}, nil } output := make([]interface{}, 0) for _, e := range *input { - rule, ok := e.(network.NatRule) + rule, ok := e.(firewallpolicyrulecollectiongroups.NatRule) if !ok { return nil, fmt.Errorf("unexpected non-nat rule: %+v", e) } diff --git a/internal/services/firewall/firewall_policy_rule_collection_group_resource_test.go b/internal/services/firewall/firewall_policy_rule_collection_group_resource_test.go index 7378922b9651..5574330b273e 100644 --- a/internal/services/firewall/firewall_policy_rule_collection_group_resource_test.go +++ b/internal/services/firewall/firewall_policy_rule_collection_group_resource_test.go @@ -8,10 +8,10 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/network/2023-04-01/firewallpolicyrulecollectiongroups" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/firewall/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -137,17 +137,17 @@ func TestAccFirewallPolicyRuleCollectionGroup_requiresImport(t *testing.T) { } func (FirewallPolicyRuleCollectionGroupResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.FirewallPolicyRuleCollectionGroupID(state.ID) + id, err := firewallpolicyrulecollectiongroups.ParseRuleCollectionGroupID(state.ID) if err != nil { return nil, err } - resp, err := clients.Firewall.FirewallPolicyRuleGroupClient.Get(ctx, id.ResourceGroup, id.FirewallPolicyName, id.RuleCollectionGroupName) + resp, err := clients.Firewall.Client.FirewallPolicyRuleCollectionGroups.Get(ctx, *id) if err != nil { return nil, fmt.Errorf("retrieving %s: %v", id.String(), err) } - return utils.Bool(resp.FirewallPolicyRuleCollectionGroupProperties != nil), nil + return utils.Bool(resp.Model != nil), nil } func (FirewallPolicyRuleCollectionGroupResource) basic(data acceptance.TestData) string { diff --git a/internal/services/firewall/firewall_resource.go b/internal/services/firewall/firewall_resource.go index e863538b68bc..f54070c02bdb 100644 --- a/internal/services/firewall/firewall_resource.go +++ b/internal/services/firewall/firewall_resource.go @@ -9,25 +9,26 @@ import ( "strings" "time" + "github.com/hashicorp/go-azure-helpers/lang/pointer" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/go-azure-helpers/resourcemanager/tags" "github.com/hashicorp/go-azure-helpers/resourcemanager/zones" + "github.com/hashicorp/go-azure-sdk/resource-manager/network/2023-04-01/azurefirewalls" + "github.com/hashicorp/go-azure-sdk/resource-manager/network/2023-04-01/firewallpolicies" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/locks" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/firewall/azuresdkhacks" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/firewall/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/firewall/validate" networkValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/network/validate" - "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" "github.com/hashicorp/terraform-provider-azurerm/utils" - "github.com/tombuildsstuff/kermit/sdk/network/2022-07-01/network" ) var AzureFirewallResourceName = "azurerm_firewall" @@ -39,7 +40,7 @@ func resourceFirewall() *pluginsdk.Resource { Update: resourceFirewallCreateUpdate, Delete: resourceFirewallDelete, Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.FirewallID(id) + _, err := azurefirewalls.ParseAzureFirewallID(id) return err }), @@ -68,8 +69,8 @@ func resourceFirewall() *pluginsdk.Resource { Required: true, ForceNew: true, ValidateFunc: validation.StringInSlice([]string{ - string(network.AzureFirewallSkuNameAZFWHub), - string(network.AzureFirewallSkuNameAZFWVNet), + string(azurefirewalls.AzureFirewallSkuNameAZFWHub), + string(azurefirewalls.AzureFirewallSkuNameAZFWVNet), }, false), }, @@ -78,16 +79,16 @@ func resourceFirewall() *pluginsdk.Resource { Type: pluginsdk.TypeString, Required: true, ValidateFunc: validation.StringInSlice([]string{ - string(network.AzureFirewallSkuTierPremium), - string(network.AzureFirewallSkuTierStandard), - string(network.AzureFirewallSkuTierBasic), + string(azurefirewalls.AzureFirewallSkuTierPremium), + string(azurefirewalls.AzureFirewallSkuTierStandard), + string(azurefirewalls.AzureFirewallSkuTierBasic), }, false), }, "firewall_policy_id": { Type: pluginsdk.TypeString, Optional: true, - ValidateFunc: validate.FirewallPolicyID, + ValidateFunc: firewallpolicies.ValidateFirewallPolicyID, }, "ip_configuration": { @@ -155,9 +156,9 @@ func resourceFirewall() *pluginsdk.Resource { Optional: true, Computed: true, ValidateFunc: validation.StringInSlice([]string{ - string(network.AzureFirewallThreatIntelModeOff), - string(network.AzureFirewallThreatIntelModeAlert), - string(network.AzureFirewallThreatIntelModeDeny), + string(azurefirewalls.AzureFirewallThreatIntelModeOff), + string(azurefirewalls.AzureFirewallThreatIntelModeAlert), + string(azurefirewalls.AzureFirewallThreatIntelModeDeny), }, false), }, @@ -216,7 +217,7 @@ func resourceFirewall() *pluginsdk.Resource { "zones": commonschema.ZonesMultipleOptionalForceNew(), - "tags": tags.Schema(), + "tags": commonschema.Tags(), }, } @@ -224,23 +225,23 @@ func resourceFirewall() *pluginsdk.Resource { } func resourceFirewallCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Firewall.AzureFirewallsClient + client := meta.(*clients.Client).Firewall.Client.AzureFirewalls subscriptionId := meta.(*clients.Client).Account.SubscriptionId ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() log.Printf("[INFO] preparing arguments for AzureRM Azure Firewall creation") - id := parse.NewFirewallID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) + id := azurefirewalls.NewAzureFirewallID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) - existing, err := client.Get(ctx, id.ResourceGroup, id.AzureFirewallName) + existing, err := client.Get(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { + if !response.WasNotFound(existing.HttpResponse) { return fmt.Errorf("checking for presence of existing %s: %s", id, err) } } - if d.IsNewResource() && !utils.ResponseWasNotFound(existing.Response) { + if d.IsNewResource() && !response.WasNotFound(existing.HttpResponse) { return tf.ImportAsExistsError("azurerm_firewall", id.ID()) } @@ -256,12 +257,12 @@ func resourceFirewallCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) e return fmt.Errorf("building list of Azure Firewall IP Configurations: %+v", err) } - parameters := network.AzureFirewall{ + parameters := azurefirewalls.AzureFirewall{ Location: &location, - AzureFirewallPropertiesFormat: &network.AzureFirewallPropertiesFormat{ + Properties: &azurefirewalls.AzureFirewallPropertiesFormat{ IPConfigurations: ipConfigs, - ThreatIntelMode: network.AzureFirewallThreatIntelMode(d.Get("threat_intel_mode").(string)), - AdditionalProperties: make(map[string]*string), + ThreatIntelMode: pointer.To(azurefirewalls.AzureFirewallThreatIntelMode(d.Get("threat_intel_mode").(string))), + AdditionalProperties: pointer.To(make(map[string]string)), }, Tags: tags.Expand(t), } @@ -286,62 +287,64 @@ func resourceFirewallCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) e *vnetToLock = append(*vnetToLock, (*mgmtVirtualNetworkName)[0]) } if *mgmtIPConfig != nil { - if parameters.IPConfigurations != nil { - for k, v := range *parameters.IPConfigurations { + if parameters.Properties.IPConfigurations != nil { + for k, v := range *parameters.Properties.IPConfigurations { if v.Name != nil && (*mgmtIPConfig)[0].Name != nil && *v.Name == *(*mgmtIPConfig)[0].Name { return fmt.Errorf("`management_ip_configuration.0.name` must not be the same as `ip_configuration.%d.name`", k) } } } - parameters.ManagementIPConfiguration = &(*mgmtIPConfig)[0] + parameters.Properties.ManagementIPConfiguration = &(*mgmtIPConfig)[0] } } if threatIntelMode := d.Get("threat_intel_mode").(string); threatIntelMode != "" { - parameters.AzureFirewallPropertiesFormat.ThreatIntelMode = network.AzureFirewallThreatIntelMode(threatIntelMode) + parameters.Properties.ThreatIntelMode = pointer.To(azurefirewalls.AzureFirewallThreatIntelMode(threatIntelMode)) } if policyId := d.Get("firewall_policy_id").(string); policyId != "" { - parameters.AzureFirewallPropertiesFormat.FirewallPolicy = &network.SubResource{ID: &policyId} + parameters.Properties.FirewallPolicy = &azurefirewalls.SubResource{Id: &policyId} } - vhub, hubIpAddresses, ok := expandFirewallVirtualHubSetting(existing, d.Get("virtual_hub").([]interface{})) + vhub, hubIpAddresses, ok := expandFirewallVirtualHubSetting(existing.Model, d.Get("virtual_hub").([]interface{})) if ok { - parameters.AzureFirewallPropertiesFormat.VirtualHub = vhub - parameters.AzureFirewallPropertiesFormat.HubIPAddresses = hubIpAddresses + parameters.Properties.VirtualHub = vhub + parameters.Properties.HubIPAddresses = hubIpAddresses } if skuName := d.Get("sku_name").(string); skuName != "" { - if parameters.Sku == nil { - parameters.Sku = &network.AzureFirewallSku{} + if parameters.Properties.Sku == nil { + parameters.Properties.Sku = &azurefirewalls.AzureFirewallSku{} } - parameters.Sku.Name = network.AzureFirewallSkuName(skuName) + parameters.Properties.Sku.Name = pointer.To(azurefirewalls.AzureFirewallSkuName(skuName)) } if skuTier := d.Get("sku_tier").(string); skuTier != "" { - if parameters.Sku == nil { - parameters.Sku = &network.AzureFirewallSku{} + if parameters.Properties.Sku == nil { + parameters.Properties.Sku = &azurefirewalls.AzureFirewallSku{} } - parameters.Sku.Tier = network.AzureFirewallSkuTier(skuTier) + parameters.Properties.Sku.Tier = pointer.To(azurefirewalls.AzureFirewallSkuTier(skuTier)) } if dnsServerSetting := expandFirewallDNSServers(d.Get("dns_servers").([]interface{})); dnsServerSetting != nil { for k, v := range dnsServerSetting { - parameters.AdditionalProperties[k] = v + attrs := *parameters.Properties.AdditionalProperties + attrs[k] = v } } if privateIpRangeSetting := expandFirewallPrivateIpRange(d.Get("private_ip_ranges").(*pluginsdk.Set).List()); privateIpRangeSetting != nil { for k, v := range privateIpRangeSetting { - parameters.AdditionalProperties[k] = v + attrs := *parameters.Properties.AdditionalProperties + attrs[k] = v } } if policyId, ok := d.GetOk("firewall_policy_id"); ok { - id, _ := parse.FirewallPolicyID(policyId.(string)) - locks.ByName(id.Name, AzureFirewallPolicyResourceName) - defer locks.UnlockByName(id.Name, AzureFirewallPolicyResourceName) + id, _ := firewallpolicies.ParseFirewallPolicyID(policyId.(string)) + locks.ByName(id.FirewallPolicyName, AzureFirewallPolicyResourceName) + defer locks.UnlockByName(id.FirewallPolicyName, AzureFirewallPolicyResourceName) } locks.ByName(id.AzureFirewallName, AzureFirewallResourceName) @@ -354,49 +357,48 @@ func resourceFirewallCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) e defer locks.UnlockMultipleByName(subnetToLock, SubnetResourceName) if !d.IsNewResource() { - exists, err2 := client.Get(ctx, id.ResourceGroup, id.AzureFirewallName) + exists, err2 := client.Get(ctx, id) if err2 != nil { - if utils.ResponseWasNotFound(exists.Response) { + if response.WasNotFound(exists.HttpResponse) { return fmt.Errorf("retrieving existing %s: firewall not found in resource group", id) } return fmt.Errorf("retrieving existing %s: %+v", id, err2) } - if exists.AzureFirewallPropertiesFormat == nil { + if exists.Model == nil { + return fmt.Errorf("retrieving existing rules for %s: `model` was nil", id) + } + + if exists.Model.Properties == nil { return fmt.Errorf("retrieving existing rules for %s: `props` was nil", id) } - props := *exists.AzureFirewallPropertiesFormat - parameters.AzureFirewallPropertiesFormat.ApplicationRuleCollections = props.ApplicationRuleCollections - parameters.AzureFirewallPropertiesFormat.NetworkRuleCollections = props.NetworkRuleCollections - parameters.AzureFirewallPropertiesFormat.NatRuleCollections = props.NatRuleCollections + props := *exists.Model.Properties + parameters.Properties.ApplicationRuleCollections = props.ApplicationRuleCollections + parameters.Properties.NetworkRuleCollections = props.NetworkRuleCollections + parameters.Properties.NatRuleCollections = props.NatRuleCollections } - future, err := client.CreateOrUpdate(ctx, id.ResourceGroup, id.AzureFirewallName, parameters) - if err != nil { + if err := client.CreateOrUpdateThenPoll(ctx, id, parameters); err != nil { return fmt.Errorf("creating/updating %s: %+v", id, err) } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for creation/update of %s: %+v", id, err) - } - d.SetId(id.ID()) return resourceFirewallRead(d, meta) } func resourceFirewallRead(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Firewall.AzureFirewallsClient + client := meta.(*clients.Client).Firewall.Client.AzureFirewalls ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.FirewallID(d.Id()) + id, err := azurefirewalls.ParseAzureFirewallID(d.Id()) if err != nil { return err } - read, err := client.Get(ctx, id.ResourceGroup, id.AzureFirewallName) + read, err := client.Get(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(read.Response) { - log.Printf("[DEBUG] Firewall %q was not found in Resource Group %q - removing from state!", id.AzureFirewallName, id.ResourceGroup) + if response.WasNotFound(read.HttpResponse) { + log.Printf("[DEBUG] Firewall %q was not found in Resource Group %q - removing from state!", id.AzureFirewallName, id.ResourceGroupName) d.SetId("") return nil } @@ -405,67 +407,71 @@ func resourceFirewallRead(d *pluginsdk.ResourceData, meta interface{}) error { } d.Set("name", id.AzureFirewallName) - d.Set("resource_group_name", id.ResourceGroup) + d.Set("resource_group_name", id.ResourceGroupName) - d.Set("location", location.NormalizeNilable(read.Location)) - d.Set("zones", zones.FlattenUntyped(read.Zones)) + if model := read.Model; model != nil { + d.Set("location", location.NormalizeNilable(model.Location)) + d.Set("zones", zones.FlattenUntyped(model.Zones)) - if props := read.AzureFirewallPropertiesFormat; props != nil { - if err := d.Set("ip_configuration", flattenFirewallIPConfigurations(props.IPConfigurations)); err != nil { - return fmt.Errorf("setting `ip_configuration`: %+v", err) - } - managementIPConfigs := make([]interface{}, 0) - if props.ManagementIPConfiguration != nil { - managementIPConfigs = flattenFirewallIPConfigurations(&[]network.AzureFirewallIPConfiguration{ - *props.ManagementIPConfiguration, - }) - } - if err := d.Set("management_ip_configuration", managementIPConfigs); err != nil { - return fmt.Errorf("setting `management_ip_configuration`: %+v", err) - } + if props := model.Properties; props != nil { + if err := d.Set("ip_configuration", flattenFirewallIPConfigurations(props.IPConfigurations)); err != nil { + return fmt.Errorf("setting `ip_configuration`: %+v", err) + } + managementIPConfigs := make([]interface{}, 0) + if props.ManagementIPConfiguration != nil { + managementIPConfigs = flattenFirewallIPConfigurations(&[]azurefirewalls.AzureFirewallIPConfiguration{ + *props.ManagementIPConfiguration, + }) + } + if err := d.Set("management_ip_configuration", managementIPConfigs); err != nil { + return fmt.Errorf("setting `management_ip_configuration`: %+v", err) + } - d.Set("threat_intel_mode", string(props.ThreatIntelMode)) + d.Set("threat_intel_mode", string(pointer.From(props.ThreatIntelMode))) - if err := d.Set("dns_servers", flattenFirewallDNSServers(props.AdditionalProperties)); err != nil { - return fmt.Errorf("setting `dns_servers`: %+v", err) - } + if err := d.Set("dns_servers", flattenFirewallDNSServers(props.AdditionalProperties)); err != nil { + return fmt.Errorf("setting `dns_servers`: %+v", err) + } - if err := d.Set("private_ip_ranges", flattenFirewallPrivateIpRange(props.AdditionalProperties)); err != nil { - return fmt.Errorf("setting `private_ip_ranges`: %+v", err) - } + if err := d.Set("private_ip_ranges", flattenFirewallPrivateIpRange(props.AdditionalProperties)); err != nil { + return fmt.Errorf("setting `private_ip_ranges`: %+v", err) + } - if policy := props.FirewallPolicy; policy != nil { - d.Set("firewall_policy_id", policy.ID) - } + if policy := props.FirewallPolicy; policy != nil { + d.Set("firewall_policy_id", policy.Id) + } - if sku := props.Sku; sku != nil { - d.Set("sku_name", string(sku.Name)) - d.Set("sku_tier", string(sku.Tier)) - } + if sku := props.Sku; sku != nil { + d.Set("sku_name", string(pointer.From(sku.Name))) + d.Set("sku_tier", string(pointer.From(sku.Tier))) + } - if err := d.Set("virtual_hub", flattenFirewallVirtualHubSetting(props)); err != nil { - return fmt.Errorf("setting `virtual_hub`: %+v", err) + if err := d.Set("virtual_hub", flattenFirewallVirtualHubSetting(props)); err != nil { + return fmt.Errorf("setting `virtual_hub`: %+v", err) + } } + + return tags.FlattenAndSet(d, model.Tags) } - return tags.FlattenAndSet(d, read.Tags) + return nil } func resourceFirewallDelete(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Firewall.AzureFirewallsClient + client := meta.(*clients.Client).Firewall.Client.AzureFirewalls ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.FirewallID(d.Id()) + id, err := azurefirewalls.ParseAzureFirewallID(d.Id()) if err != nil { return err } - read, err := client.Get(ctx, id.ResourceGroup, id.AzureFirewallName) + read, err := client.Get(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(read.Response) { + if response.WasNotFound(read.HttpResponse) { // deleted outside of TF - log.Printf("[DEBUG] Firewall %q was not found in Resource Group %q - assuming removed!", id.AzureFirewallName, id.ResourceGroup) + log.Printf("[DEBUG] Firewall %q was not found in Resource Group %q - assuming removed!", id.AzureFirewallName, id.ResourceGroupName) return nil } @@ -474,76 +480,83 @@ func resourceFirewallDelete(d *pluginsdk.ResourceData, meta interface{}) error { subnetNamesToLock := make([]string, 0) virtualNetworkNamesToLock := make([]string, 0) - if props := read.AzureFirewallPropertiesFormat; props != nil { - if configs := props.IPConfigurations; configs != nil { - for _, config := range *configs { - if config.Subnet == nil || config.Subnet.ID == nil { - continue - } + if model := read.Model; model != nil { + if props := model.Properties; props != nil { + if configs := props.IPConfigurations; configs != nil { + for _, config := range *configs { + if config.Properties == nil || config.Properties.Subnet == nil || config.Properties.Subnet.Id == nil { + continue + } - parsedSubnetID, err2 := commonids.ParseSubnetID(*config.Subnet.ID) - if err2 != nil { - return err2 - } + parsedSubnetID, err2 := commonids.ParseSubnetID(*config.Properties.Subnet.Id) + if err2 != nil { + return err2 + } - if !utils.SliceContainsValue(subnetNamesToLock, parsedSubnetID.SubnetName) { - subnetNamesToLock = append(subnetNamesToLock, parsedSubnetID.SubnetName) - } + if !utils.SliceContainsValue(subnetNamesToLock, parsedSubnetID.SubnetName) { + subnetNamesToLock = append(subnetNamesToLock, parsedSubnetID.SubnetName) + } - if !utils.SliceContainsValue(virtualNetworkNamesToLock, parsedSubnetID.VirtualNetworkName) { - virtualNetworkNamesToLock = append(virtualNetworkNamesToLock, parsedSubnetID.VirtualNetworkName) + if !utils.SliceContainsValue(virtualNetworkNamesToLock, parsedSubnetID.VirtualNetworkName) { + virtualNetworkNamesToLock = append(virtualNetworkNamesToLock, parsedSubnetID.VirtualNetworkName) + } } } - } - if mconfig := props.ManagementIPConfiguration; mconfig != nil { - if mconfig.Subnet != nil && mconfig.Subnet.ID != nil { - parsedSubnetID, err2 := commonids.ParseSubnetID(*mconfig.Subnet.ID) - if err2 != nil { - return err2 - } + if mconfig := props.ManagementIPConfiguration; mconfig != nil { + if mconfig.Properties != nil && mconfig.Properties.Subnet != nil && mconfig.Properties.Subnet.Id != nil { + parsedSubnetID, err2 := commonids.ParseSubnetID(*mconfig.Properties.Subnet.Id) + if err2 != nil { + return err2 + } - if !utils.SliceContainsValue(subnetNamesToLock, parsedSubnetID.SubnetName) { - subnetNamesToLock = append(subnetNamesToLock, parsedSubnetID.SubnetName) - } + if !utils.SliceContainsValue(subnetNamesToLock, parsedSubnetID.SubnetName) { + subnetNamesToLock = append(subnetNamesToLock, parsedSubnetID.SubnetName) + } - if !utils.SliceContainsValue(virtualNetworkNamesToLock, parsedSubnetID.VirtualNetworkName) { - virtualNetworkNamesToLock = append(virtualNetworkNamesToLock, parsedSubnetID.VirtualNetworkName) + if !utils.SliceContainsValue(virtualNetworkNamesToLock, parsedSubnetID.VirtualNetworkName) { + virtualNetworkNamesToLock = append(virtualNetworkNamesToLock, parsedSubnetID.VirtualNetworkName) + } } } } - } - if read.FirewallPolicy != nil && read.FirewallPolicy.ID != nil { - id, _ := parse.FirewallPolicyID(*read.FirewallPolicy.ID) - locks.ByName(id.Name, AzureFirewallPolicyResourceName) - defer locks.UnlockByName(id.Name, AzureFirewallPolicyResourceName) - } + if read.Model.Properties != nil && read.Model.Properties.FirewallPolicy != nil && read.Model.Properties.FirewallPolicy.Id != nil { + id, _ := firewallpolicies.ParseFirewallPolicyID(*read.Model.Properties.FirewallPolicy.Id) + locks.ByName(id.FirewallPolicyName, AzureFirewallPolicyResourceName) + defer locks.UnlockByName(id.FirewallPolicyName, AzureFirewallPolicyResourceName) + } - locks.ByName(id.AzureFirewallName, AzureFirewallResourceName) - defer locks.UnlockByName(id.AzureFirewallName, AzureFirewallResourceName) + locks.ByName(id.AzureFirewallName, AzureFirewallResourceName) + defer locks.UnlockByName(id.AzureFirewallName, AzureFirewallResourceName) - locks.MultipleByName(&virtualNetworkNamesToLock, VirtualNetworkResourceName) - defer locks.UnlockMultipleByName(&virtualNetworkNamesToLock, VirtualNetworkResourceName) + locks.MultipleByName(&virtualNetworkNamesToLock, VirtualNetworkResourceName) + defer locks.UnlockMultipleByName(&virtualNetworkNamesToLock, VirtualNetworkResourceName) - locks.MultipleByName(&subnetNamesToLock, SubnetResourceName) - defer locks.UnlockMultipleByName(&subnetNamesToLock, SubnetResourceName) + locks.MultipleByName(&subnetNamesToLock, SubnetResourceName) + defer locks.UnlockMultipleByName(&subnetNamesToLock, SubnetResourceName) - // Change this back to using the SDK method once https://github.com/Azure/azure-sdk-for-go/issues/17013 is addressed. - future, err := azuresdkhacks.DeleteFirewall(ctx, client, id.ResourceGroup, id.AzureFirewallName) - if err != nil { - return fmt.Errorf("deleting Azure Firewall %s : %+v", *id, err) - } + // todo see if this is still needed this way + /* + // Change this back to using the SDK method once https://github.com/Azure/azure-sdk-for-go/issues/17013 is addressed. + future, err := azuresdkhacks.DeleteFirewall(ctx, client, id.ResourceGroup, id.AzureFirewallName) + if err != nil { + return fmt.Errorf("deleting Azure Firewall %s : %+v", *id, err) + } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for the deletion of Azure Firewall %s : %+v", *id, err) + if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { + return fmt.Errorf("waiting for the deletion of Azure Firewall %s : %+v", *id, err) + } + */ + + return client.DeleteThenPoll(ctx, *id) } return err } -func expandFirewallIPConfigurations(configs []interface{}) (*[]network.AzureFirewallIPConfiguration, *[]string, *[]string, error) { - ipConfigs := make([]network.AzureFirewallIPConfiguration, 0) +func expandFirewallIPConfigurations(configs []interface{}) (*[]azurefirewalls.AzureFirewallIPConfiguration, *[]string, *[]string, error) { + ipConfigs := make([]azurefirewalls.AzureFirewallIPConfiguration, 0) subnetNamesToLock := make([]string, 0) virtualNetworkNamesToLock := make([]string, 0) @@ -553,14 +566,14 @@ func expandFirewallIPConfigurations(configs []interface{}) (*[]network.AzureFire subnetId := data["subnet_id"].(string) pubID := data["public_ip_address_id"].(string) - ipConfig := network.AzureFirewallIPConfiguration{ - Name: utils.String(name), - AzureFirewallIPConfigurationPropertiesFormat: &network.AzureFirewallIPConfigurationPropertiesFormat{}, + ipConfig := azurefirewalls.AzureFirewallIPConfiguration{ + Name: utils.String(name), + Properties: &azurefirewalls.AzureFirewallIPConfigurationPropertiesFormat{}, } if pubID != "" { - ipConfig.AzureFirewallIPConfigurationPropertiesFormat.PublicIPAddress = &network.SubResource{ - ID: utils.String(pubID), + ipConfig.Properties.PublicIPAddress = &azurefirewalls.SubResource{ + Id: utils.String(pubID), } } @@ -578,8 +591,8 @@ func expandFirewallIPConfigurations(configs []interface{}) (*[]network.AzureFire virtualNetworkNamesToLock = append(virtualNetworkNamesToLock, subnetID.VirtualNetworkName) } - ipConfig.AzureFirewallIPConfigurationPropertiesFormat.Subnet = &network.SubResource{ - ID: utils.String(subnetId), + ipConfig.Properties.Subnet = &azurefirewalls.SubResource{ + Id: utils.String(subnetId), } } ipConfigs = append(ipConfigs, ipConfig) @@ -587,7 +600,7 @@ func expandFirewallIPConfigurations(configs []interface{}) (*[]network.AzureFire return &ipConfigs, &subnetNamesToLock, &virtualNetworkNamesToLock, nil } -func flattenFirewallIPConfigurations(input *[]network.AzureFirewallIPConfiguration) []interface{} { +func flattenFirewallIPConfigurations(input *[]azurefirewalls.AzureFirewallIPConfiguration) []interface{} { result := make([]interface{}, 0) if input == nil { return result @@ -595,7 +608,7 @@ func flattenFirewallIPConfigurations(input *[]network.AzureFirewallIPConfigurati for _, v := range *input { afIPConfig := make(map[string]interface{}) - props := v.AzureFirewallIPConfigurationPropertiesFormat + props := v.Properties if props == nil { continue } @@ -605,7 +618,7 @@ func flattenFirewallIPConfigurations(input *[]network.AzureFirewallIPConfigurati } if subnet := props.Subnet; subnet != nil { - if id := subnet.ID; id != nil { + if id := subnet.Id; id != nil { afIPConfig["subnet_id"] = *id } } @@ -615,7 +628,7 @@ func flattenFirewallIPConfigurations(input *[]network.AzureFirewallIPConfigurati } if pip := props.PublicIPAddress; pip != nil { - if id := pip.ID; id != nil { + if id := pip.Id; id != nil { afIPConfig["public_ip_address_id"] = *id } } @@ -625,7 +638,7 @@ func flattenFirewallIPConfigurations(input *[]network.AzureFirewallIPConfigurati return result } -func expandFirewallDNSServers(input []interface{}) map[string]*string { +func expandFirewallDNSServers(input []interface{}) map[string]string { if len(input) == 0 { return nil } @@ -636,34 +649,29 @@ func expandFirewallDNSServers(input []interface{}) map[string]*string { } // Swagger issue asking finalize these properties: https://github.com/Azure/azure-rest-api-specs/issues/11278 - return map[string]*string{ - "Network.DNS.EnableProxy": utils.String("true"), - "Network.DNS.Servers": utils.String(strings.Join(servers, ",")), + return map[string]string{ + "Network.DNS.EnableProxy": "true", + "Network.DNS.Servers": strings.Join(servers, ","), } } -func flattenFirewallDNSServers(input map[string]*string) []interface{} { - if len(input) == 0 { +func flattenFirewallDNSServers(input *map[string]string) []interface{} { + if input == nil || len(*input) == 0 { return nil } - enabled := false - if enabledPtr := input["Network.DNS.EnableProxy"]; enabledPtr != nil { - enabled = *enabledPtr == "true" - } + attrs := *input + enabled := attrs["Network.DNS.EnableProxy"] == "true" if !enabled { return nil } - servers := []string{} - if serversPtr := input["Network.DNS.Servers"]; serversPtr != nil { - servers = strings.Split(*serversPtr, ",") - } + servers := strings.Split(attrs["Network.DNS.Servers"], ",") return utils.FlattenStringSlice(&servers) } -func expandFirewallPrivateIpRange(input []interface{}) map[string]*string { +func expandFirewallPrivateIpRange(input []interface{}) map[string]string { if len(input) == 0 { return nil } @@ -674,24 +682,25 @@ func expandFirewallPrivateIpRange(input []interface{}) map[string]*string { } // Swagger issue asking finalize these properties: https://github.com/Azure/azure-rest-api-specs/issues/10015 - return map[string]*string{ - "Network.SNAT.PrivateRanges": utils.String(strings.Join(rangeSlice, ",")), + return map[string]string{ + "Network.SNAT.PrivateRanges": strings.Join(rangeSlice, ","), } } -func flattenFirewallPrivateIpRange(input map[string]*string) []interface{} { - if len(input) == 0 { +func flattenFirewallPrivateIpRange(input *map[string]string) []interface{} { + if input == nil && len(*input) == 0 { return nil } + attrs := *input rangeSlice := []string{} - if privateIpRanges := input["Network.SNAT.PrivateRanges"]; privateIpRanges != nil { - rangeSlice = strings.Split(*privateIpRanges, ",") + if privateIpRanges := attrs["Network.SNAT.PrivateRanges"]; privateIpRanges != "" { + rangeSlice = strings.Split(attrs["Network.SNAT.PrivateRanges"], ",") } return utils.FlattenStringSlice(&rangeSlice) } -func expandFirewallVirtualHubSetting(existing network.AzureFirewall, input []interface{}) (vhub *network.SubResource, ipAddresses *network.HubIPAddresses, ok bool) { +func expandFirewallVirtualHubSetting(existing *azurefirewalls.AzureFirewall, input []interface{}) (vhub *azurefirewalls.SubResource, ipAddresses *azurefirewalls.HubIPAddresses, ok bool) { if len(input) == 0 { return nil, nil, false } @@ -706,31 +715,33 @@ func expandFirewallVirtualHubSetting(existing network.AzureFirewall, input []int // Scale up: "Addresses" should remain same as before scaling up // Scale down: "Addresses" should indicate the addresses to be retained (in this case we retain the first new "Count" ones) newCount := b["public_ip_count"].(int) - var addresses *[]network.AzureFirewallPublicIPAddress - if prop := existing.AzureFirewallPropertiesFormat; prop != nil { - if ipaddress := prop.HubIPAddresses; ipaddress != nil { - if pips := ipaddress.PublicIPs; pips != nil { - if count := pips.Count; count != nil { - oldCount := int(*count) - addresses = pips.Addresses - - // In case of scale down, keep the first new "Count" addresses. - if oldCount > newCount { - keptAddresses := make([]network.AzureFirewallPublicIPAddress, newCount) - for i := 0; i < newCount; i++ { - keptAddresses[i] = (*addresses)[i] + var addresses *[]azurefirewalls.AzureFirewallPublicIPAddress + if existing != nil { + if prop := existing.Properties; prop != nil { + if ipaddress := prop.HubIPAddresses; ipaddress != nil { + if pips := ipaddress.PublicIPs; pips != nil { + if count := pips.Count; count != nil { + oldCount := int(*count) + addresses = pips.Addresses + + // In case of scale down, keep the first new "Count" addresses. + if oldCount > newCount { + keptAddresses := make([]azurefirewalls.AzureFirewallPublicIPAddress, newCount) + for i := 0; i < newCount; i++ { + keptAddresses[i] = (*addresses)[i] + } + addresses = &keptAddresses } - addresses = &keptAddresses } } } } } - vhub = &network.SubResource{ID: utils.String(b["virtual_hub_id"].(string))} - ipAddresses = &network.HubIPAddresses{ - PublicIPs: &network.HubPublicIPAddresses{ - Count: utils.Int32(int32(b["public_ip_count"].(int))), + vhub = &azurefirewalls.SubResource{Id: utils.String(b["virtual_hub_id"].(string))} + ipAddresses = &azurefirewalls.HubIPAddresses{ + PublicIPs: &azurefirewalls.HubPublicIPAddresses{ + Count: utils.Int64(int64(b["public_ip_count"].(int))), Addresses: addresses, }, } @@ -738,14 +749,14 @@ func expandFirewallVirtualHubSetting(existing network.AzureFirewall, input []int return vhub, ipAddresses, true } -func flattenFirewallVirtualHubSetting(props *network.AzureFirewallPropertiesFormat) []interface{} { +func flattenFirewallVirtualHubSetting(props *azurefirewalls.AzureFirewallPropertiesFormat) []interface{} { if props.VirtualHub == nil { return nil } var vhubId string - if props.VirtualHub.ID != nil { - vhubId = *props.VirtualHub.ID + if props.VirtualHub.Id != nil { + vhubId = *props.VirtualHub.Id } var ( diff --git a/internal/services/firewall/firewall_resource_test.go b/internal/services/firewall/firewall_resource_test.go index 3b039f1b6bd4..12329ca15844 100644 --- a/internal/services/firewall/firewall_resource_test.go +++ b/internal/services/firewall/firewall_resource_test.go @@ -10,10 +10,10 @@ import ( "strings" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/network/2023-04-01/azurefirewalls" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/firewall/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -376,34 +376,29 @@ func TestAccFirewall_privateRanges(t *testing.T) { } func (FirewallResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.FirewallID(state.ID) + id, err := azurefirewalls.ParseAzureFirewallID(state.ID) if err != nil { return nil, err } - resp, err := clients.Firewall.AzureFirewallsClient.Get(ctx, id.ResourceGroup, id.AzureFirewallName) + resp, err := clients.Firewall.Client.AzureFirewalls.Get(ctx, *id) if err != nil { return nil, fmt.Errorf("retrieving Azure Firewall %s : %v", *id, err) } - return utils.Bool(resp.AzureFirewallPropertiesFormat != nil), nil + return utils.Bool(resp.Model != nil), nil } func (FirewallResource) Destroy(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.FirewallID(state.ID) + id, err := azurefirewalls.ParseAzureFirewallID(state.ID) if err != nil { return nil, err } - future, err := clients.Firewall.AzureFirewallsClient.Delete(ctx, id.ResourceGroup, id.AzureFirewallName) - if err != nil { + if err = clients.Firewall.Client.AzureFirewalls.DeleteThenPoll(ctx, *id); err != nil { return nil, fmt.Errorf("deleting Azure Firewall %q: %+v", id.AzureFirewallName, err) } - if err = future.WaitForCompletionRef(ctx, clients.Firewall.AzureFirewallsClient.Client); err != nil { - return nil, fmt.Errorf("waiting for Deletion on azureFirewallsClient: %+v", err) - } - return utils.Bool(true), nil } diff --git a/internal/services/firewall/parse/firewall.go b/internal/services/firewall/parse/firewall.go deleted file mode 100644 index 18d543cae80a..000000000000 --- a/internal/services/firewall/parse/firewall.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package parse - -// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten - -import ( - "fmt" - "strings" - - "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" -) - -type FirewallId struct { - SubscriptionId string - ResourceGroup string - AzureFirewallName string -} - -func NewFirewallID(subscriptionId, resourceGroup, azureFirewallName string) FirewallId { - return FirewallId{ - SubscriptionId: subscriptionId, - ResourceGroup: resourceGroup, - AzureFirewallName: azureFirewallName, - } -} - -func (id FirewallId) String() string { - segments := []string{ - fmt.Sprintf("Azure Firewall Name %q", id.AzureFirewallName), - fmt.Sprintf("Resource Group %q", id.ResourceGroup), - } - segmentsStr := strings.Join(segments, " / ") - return fmt.Sprintf("%s: (%s)", "Firewall", segmentsStr) -} - -func (id FirewallId) ID() string { - fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/azureFirewalls/%s" - return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroup, id.AzureFirewallName) -} - -// FirewallID parses a Firewall ID into an FirewallId struct -func FirewallID(input string) (*FirewallId, error) { - id, err := resourceids.ParseAzureResourceID(input) - if err != nil { - return nil, fmt.Errorf("parsing %q as an Firewall ID: %+v", input, err) - } - - resourceId := FirewallId{ - SubscriptionId: id.SubscriptionID, - ResourceGroup: id.ResourceGroup, - } - - if resourceId.SubscriptionId == "" { - return nil, fmt.Errorf("ID was missing the 'subscriptions' element") - } - - if resourceId.ResourceGroup == "" { - return nil, fmt.Errorf("ID was missing the 'resourceGroups' element") - } - - if resourceId.AzureFirewallName, err = id.PopSegment("azureFirewalls"); err != nil { - return nil, err - } - - if err := id.ValidateNoEmptySegments(input); err != nil { - return nil, err - } - - return &resourceId, nil -} diff --git a/internal/services/firewall/parse/firewall_policy.go b/internal/services/firewall/parse/firewall_policy.go deleted file mode 100644 index 197c0f953bef..000000000000 --- a/internal/services/firewall/parse/firewall_policy.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package parse - -// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten - -import ( - "fmt" - "strings" - - "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" -) - -type FirewallPolicyId struct { - SubscriptionId string - ResourceGroup string - Name string -} - -func NewFirewallPolicyID(subscriptionId, resourceGroup, name string) FirewallPolicyId { - return FirewallPolicyId{ - SubscriptionId: subscriptionId, - ResourceGroup: resourceGroup, - Name: name, - } -} - -func (id FirewallPolicyId) String() string { - segments := []string{ - fmt.Sprintf("Name %q", id.Name), - fmt.Sprintf("Resource Group %q", id.ResourceGroup), - } - segmentsStr := strings.Join(segments, " / ") - return fmt.Sprintf("%s: (%s)", "Firewall Policy", segmentsStr) -} - -func (id FirewallPolicyId) ID() string { - fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/firewallPolicies/%s" - return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroup, id.Name) -} - -// FirewallPolicyID parses a FirewallPolicy ID into an FirewallPolicyId struct -func FirewallPolicyID(input string) (*FirewallPolicyId, error) { - id, err := resourceids.ParseAzureResourceID(input) - if err != nil { - return nil, fmt.Errorf("parsing %q as an FirewallPolicy ID: %+v", input, err) - } - - resourceId := FirewallPolicyId{ - SubscriptionId: id.SubscriptionID, - ResourceGroup: id.ResourceGroup, - } - - if resourceId.SubscriptionId == "" { - return nil, fmt.Errorf("ID was missing the 'subscriptions' element") - } - - if resourceId.ResourceGroup == "" { - return nil, fmt.Errorf("ID was missing the 'resourceGroups' element") - } - - if resourceId.Name, err = id.PopSegment("firewallPolicies"); err != nil { - return nil, err - } - - if err := id.ValidateNoEmptySegments(input); err != nil { - return nil, err - } - - return &resourceId, nil -} diff --git a/internal/services/firewall/parse/firewall_policy_rule_collection_group.go b/internal/services/firewall/parse/firewall_policy_rule_collection_group.go deleted file mode 100644 index dfe6518bc52d..000000000000 --- a/internal/services/firewall/parse/firewall_policy_rule_collection_group.go +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package parse - -// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten - -import ( - "fmt" - "strings" - - "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" -) - -type FirewallPolicyRuleCollectionGroupId struct { - SubscriptionId string - ResourceGroup string - FirewallPolicyName string - RuleCollectionGroupName string -} - -func NewFirewallPolicyRuleCollectionGroupID(subscriptionId, resourceGroup, firewallPolicyName, ruleCollectionGroupName string) FirewallPolicyRuleCollectionGroupId { - return FirewallPolicyRuleCollectionGroupId{ - SubscriptionId: subscriptionId, - ResourceGroup: resourceGroup, - FirewallPolicyName: firewallPolicyName, - RuleCollectionGroupName: ruleCollectionGroupName, - } -} - -func (id FirewallPolicyRuleCollectionGroupId) String() string { - segments := []string{ - fmt.Sprintf("Rule Collection Group Name %q", id.RuleCollectionGroupName), - fmt.Sprintf("Firewall Policy Name %q", id.FirewallPolicyName), - fmt.Sprintf("Resource Group %q", id.ResourceGroup), - } - segmentsStr := strings.Join(segments, " / ") - return fmt.Sprintf("%s: (%s)", "Firewall Policy Rule Collection Group", segmentsStr) -} - -func (id FirewallPolicyRuleCollectionGroupId) ID() string { - fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/firewallPolicies/%s/ruleCollectionGroups/%s" - return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroup, id.FirewallPolicyName, id.RuleCollectionGroupName) -} - -// FirewallPolicyRuleCollectionGroupID parses a FirewallPolicyRuleCollectionGroup ID into an FirewallPolicyRuleCollectionGroupId struct -func FirewallPolicyRuleCollectionGroupID(input string) (*FirewallPolicyRuleCollectionGroupId, error) { - id, err := resourceids.ParseAzureResourceID(input) - if err != nil { - return nil, fmt.Errorf("parsing %q as an FirewallPolicyRuleCollectionGroup ID: %+v", input, err) - } - - resourceId := FirewallPolicyRuleCollectionGroupId{ - SubscriptionId: id.SubscriptionID, - ResourceGroup: id.ResourceGroup, - } - - if resourceId.SubscriptionId == "" { - return nil, fmt.Errorf("ID was missing the 'subscriptions' element") - } - - if resourceId.ResourceGroup == "" { - return nil, fmt.Errorf("ID was missing the 'resourceGroups' element") - } - - if resourceId.FirewallPolicyName, err = id.PopSegment("firewallPolicies"); err != nil { - return nil, err - } - if resourceId.RuleCollectionGroupName, err = id.PopSegment("ruleCollectionGroups"); err != nil { - return nil, err - } - - if err := id.ValidateNoEmptySegments(input); err != nil { - return nil, err - } - - return &resourceId, nil -} diff --git a/internal/services/firewall/parse/firewall_policy_rule_collection_group_test.go b/internal/services/firewall/parse/firewall_policy_rule_collection_group_test.go deleted file mode 100644 index 7c9a33e4c2af..000000000000 --- a/internal/services/firewall/parse/firewall_policy_rule_collection_group_test.go +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package parse - -// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten - -import ( - "testing" - - "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" -) - -var _ resourceids.Id = FirewallPolicyRuleCollectionGroupId{} - -func TestFirewallPolicyRuleCollectionGroupIDFormatter(t *testing.T) { - actual := NewFirewallPolicyRuleCollectionGroupID("12345678-1234-9876-4563-123456789012", "resGroup1", "policy1", "ruleCollectionGroup1").ID() - expected := "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Network/firewallPolicies/policy1/ruleCollectionGroups/ruleCollectionGroup1" - if actual != expected { - t.Fatalf("Expected %q but got %q", expected, actual) - } -} - -func TestFirewallPolicyRuleCollectionGroupID(t *testing.T) { - testData := []struct { - Input string - Error bool - Expected *FirewallPolicyRuleCollectionGroupId - }{ - - { - // empty - Input: "", - Error: true, - }, - - { - // missing SubscriptionId - Input: "/", - Error: true, - }, - - { - // missing value for SubscriptionId - Input: "/subscriptions/", - Error: true, - }, - - { - // missing ResourceGroup - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/", - Error: true, - }, - - { - // missing value for ResourceGroup - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/", - Error: true, - }, - - { - // missing FirewallPolicyName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Network/", - Error: true, - }, - - { - // missing value for FirewallPolicyName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Network/firewallPolicies/", - Error: true, - }, - - { - // missing RuleCollectionGroupName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Network/firewallPolicies/policy1/", - Error: true, - }, - - { - // missing value for RuleCollectionGroupName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Network/firewallPolicies/policy1/ruleCollectionGroups/", - Error: true, - }, - - { - // valid - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Network/firewallPolicies/policy1/ruleCollectionGroups/ruleCollectionGroup1", - Expected: &FirewallPolicyRuleCollectionGroupId{ - SubscriptionId: "12345678-1234-9876-4563-123456789012", - ResourceGroup: "resGroup1", - FirewallPolicyName: "policy1", - RuleCollectionGroupName: "ruleCollectionGroup1", - }, - }, - - { - // upper-cased - Input: "/SUBSCRIPTIONS/12345678-1234-9876-4563-123456789012/RESOURCEGROUPS/RESGROUP1/PROVIDERS/MICROSOFT.NETWORK/FIREWALLPOLICIES/POLICY1/RULECOLLECTIONGROUPS/RULECOLLECTIONGROUP1", - Error: true, - }, - } - - for _, v := range testData { - t.Logf("[DEBUG] Testing %q", v.Input) - - actual, err := FirewallPolicyRuleCollectionGroupID(v.Input) - if err != nil { - if v.Error { - continue - } - - t.Fatalf("Expect a value but got an error: %s", err) - } - if v.Error { - t.Fatal("Expect an error but didn't get one") - } - - if actual.SubscriptionId != v.Expected.SubscriptionId { - t.Fatalf("Expected %q but got %q for SubscriptionId", v.Expected.SubscriptionId, actual.SubscriptionId) - } - if actual.ResourceGroup != v.Expected.ResourceGroup { - t.Fatalf("Expected %q but got %q for ResourceGroup", v.Expected.ResourceGroup, actual.ResourceGroup) - } - if actual.FirewallPolicyName != v.Expected.FirewallPolicyName { - t.Fatalf("Expected %q but got %q for FirewallPolicyName", v.Expected.FirewallPolicyName, actual.FirewallPolicyName) - } - if actual.RuleCollectionGroupName != v.Expected.RuleCollectionGroupName { - t.Fatalf("Expected %q but got %q for RuleCollectionGroupName", v.Expected.RuleCollectionGroupName, actual.RuleCollectionGroupName) - } - } -} diff --git a/internal/services/firewall/parse/firewall_policy_test.go b/internal/services/firewall/parse/firewall_policy_test.go deleted file mode 100644 index 15988b1baf55..000000000000 --- a/internal/services/firewall/parse/firewall_policy_test.go +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package parse - -// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten - -import ( - "testing" - - "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" -) - -var _ resourceids.Id = FirewallPolicyId{} - -func TestFirewallPolicyIDFormatter(t *testing.T) { - actual := NewFirewallPolicyID("12345678-1234-9876-4563-123456789012", "resGroup1", "policy1").ID() - expected := "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Network/firewallPolicies/policy1" - if actual != expected { - t.Fatalf("Expected %q but got %q", expected, actual) - } -} - -func TestFirewallPolicyID(t *testing.T) { - testData := []struct { - Input string - Error bool - Expected *FirewallPolicyId - }{ - - { - // empty - Input: "", - Error: true, - }, - - { - // missing SubscriptionId - Input: "/", - Error: true, - }, - - { - // missing value for SubscriptionId - Input: "/subscriptions/", - Error: true, - }, - - { - // missing ResourceGroup - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/", - Error: true, - }, - - { - // missing value for ResourceGroup - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/", - Error: true, - }, - - { - // missing Name - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Network/", - Error: true, - }, - - { - // missing value for Name - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Network/firewallPolicies/", - Error: true, - }, - - { - // valid - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Network/firewallPolicies/policy1", - Expected: &FirewallPolicyId{ - SubscriptionId: "12345678-1234-9876-4563-123456789012", - ResourceGroup: "resGroup1", - Name: "policy1", - }, - }, - - { - // upper-cased - Input: "/SUBSCRIPTIONS/12345678-1234-9876-4563-123456789012/RESOURCEGROUPS/RESGROUP1/PROVIDERS/MICROSOFT.NETWORK/FIREWALLPOLICIES/POLICY1", - Error: true, - }, - } - - for _, v := range testData { - t.Logf("[DEBUG] Testing %q", v.Input) - - actual, err := FirewallPolicyID(v.Input) - if err != nil { - if v.Error { - continue - } - - t.Fatalf("Expect a value but got an error: %s", err) - } - if v.Error { - t.Fatal("Expect an error but didn't get one") - } - - if actual.SubscriptionId != v.Expected.SubscriptionId { - t.Fatalf("Expected %q but got %q for SubscriptionId", v.Expected.SubscriptionId, actual.SubscriptionId) - } - if actual.ResourceGroup != v.Expected.ResourceGroup { - t.Fatalf("Expected %q but got %q for ResourceGroup", v.Expected.ResourceGroup, actual.ResourceGroup) - } - if actual.Name != v.Expected.Name { - t.Fatalf("Expected %q but got %q for Name", v.Expected.Name, actual.Name) - } - } -} diff --git a/internal/services/firewall/parse/firewall_test.go b/internal/services/firewall/parse/firewall_test.go deleted file mode 100644 index d1feb6b7ebbf..000000000000 --- a/internal/services/firewall/parse/firewall_test.go +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package parse - -// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten - -import ( - "testing" - - "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" -) - -var _ resourceids.Id = FirewallId{} - -func TestFirewallIDFormatter(t *testing.T) { - actual := NewFirewallID("12345678-1234-9876-4563-123456789012", "group1", "firewall1").ID() - expected := "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/group1/providers/Microsoft.Network/azureFirewalls/firewall1" - if actual != expected { - t.Fatalf("Expected %q but got %q", expected, actual) - } -} - -func TestFirewallID(t *testing.T) { - testData := []struct { - Input string - Error bool - Expected *FirewallId - }{ - - { - // empty - Input: "", - Error: true, - }, - - { - // missing SubscriptionId - Input: "/", - Error: true, - }, - - { - // missing value for SubscriptionId - Input: "/subscriptions/", - Error: true, - }, - - { - // missing ResourceGroup - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/", - Error: true, - }, - - { - // missing value for ResourceGroup - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/", - Error: true, - }, - - { - // missing AzureFirewallName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/group1/providers/Microsoft.Network/", - Error: true, - }, - - { - // missing value for AzureFirewallName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/group1/providers/Microsoft.Network/azureFirewalls/", - Error: true, - }, - - { - // valid - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/group1/providers/Microsoft.Network/azureFirewalls/firewall1", - Expected: &FirewallId{ - SubscriptionId: "12345678-1234-9876-4563-123456789012", - ResourceGroup: "group1", - AzureFirewallName: "firewall1", - }, - }, - - { - // upper-cased - Input: "/SUBSCRIPTIONS/12345678-1234-9876-4563-123456789012/RESOURCEGROUPS/GROUP1/PROVIDERS/MICROSOFT.NETWORK/AZUREFIREWALLS/FIREWALL1", - Error: true, - }, - } - - for _, v := range testData { - t.Logf("[DEBUG] Testing %q", v.Input) - - actual, err := FirewallID(v.Input) - if err != nil { - if v.Error { - continue - } - - t.Fatalf("Expect a value but got an error: %s", err) - } - if v.Error { - t.Fatal("Expect an error but didn't get one") - } - - if actual.SubscriptionId != v.Expected.SubscriptionId { - t.Fatalf("Expected %q but got %q for SubscriptionId", v.Expected.SubscriptionId, actual.SubscriptionId) - } - if actual.ResourceGroup != v.Expected.ResourceGroup { - t.Fatalf("Expected %q but got %q for ResourceGroup", v.Expected.ResourceGroup, actual.ResourceGroup) - } - if actual.AzureFirewallName != v.Expected.AzureFirewallName { - t.Fatalf("Expected %q but got %q for AzureFirewallName", v.Expected.AzureFirewallName, actual.AzureFirewallName) - } - } -} diff --git a/internal/services/firewall/resourceids.go b/internal/services/firewall/resourceids.go index 28d61aed6ca7..86aa5ad9b6ef 100644 --- a/internal/services/firewall/resourceids.go +++ b/internal/services/firewall/resourceids.go @@ -4,9 +4,6 @@ package firewall // Firewall Policy -//go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=Firewall -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/group1/providers/Microsoft.Network/azureFirewalls/firewall1 //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=FirewallApplicationRuleCollection -id=/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mygroup1/providers/Microsoft.Network/azureFirewalls/myfirewall/applicationRuleCollections/applicationRuleCollection1 //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=FirewallNatRuleCollection -id=/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mygroup1/providers/Microsoft.Network/azureFirewalls/myfirewall/natRuleCollections/natRuleCollection1 //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=FirewallNetworkRuleCollection -id=/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mygroup1/providers/Microsoft.Network/azureFirewalls/myfirewall/networkRuleCollections/networkRuleCollection1 -//go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=FirewallPolicy -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Network/firewallPolicies/policy1 -//go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=FirewallPolicyRuleCollectionGroup -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Network/firewallPolicies/policy1/ruleCollectionGroups/ruleCollectionGroup1 diff --git a/internal/services/firewall/subresource.go b/internal/services/firewall/subresource.go index e28c16aabe6c..f6b7c3a0c9b7 100644 --- a/internal/services/firewall/subresource.go +++ b/internal/services/firewall/subresource.go @@ -4,18 +4,18 @@ package firewall import ( - "github.com/tombuildsstuff/kermit/sdk/network/2022-07-01/network" + "github.com/hashicorp/go-azure-sdk/resource-manager/network/2023-04-01/firewallpolicies" ) -func flattenNetworkSubResourceID(input *[]network.SubResource) []interface{} { +func flattenNetworkSubResourceID(input *[]firewallpolicies.SubResource) []interface{} { results := make([]interface{}, 0) if input == nil { return results } for _, item := range *input { - if item.ID != nil { - results = append(results, *item.ID) + if item.Id != nil { + results = append(results, *item.Id) } } diff --git a/internal/services/firewall/validate/firewall_id.go b/internal/services/firewall/validate/firewall_id.go deleted file mode 100644 index 25867ade297c..000000000000 --- a/internal/services/firewall/validate/firewall_id.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package validate - -// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten - -import ( - "fmt" - - "github.com/hashicorp/terraform-provider-azurerm/internal/services/firewall/parse" -) - -func FirewallID(input interface{}, key string) (warnings []string, errors []error) { - v, ok := input.(string) - if !ok { - errors = append(errors, fmt.Errorf("expected %q to be a string", key)) - return - } - - if _, err := parse.FirewallID(v); err != nil { - errors = append(errors, err) - } - - return -} diff --git a/internal/services/firewall/validate/firewall_id_test.go b/internal/services/firewall/validate/firewall_id_test.go deleted file mode 100644 index 770d28c0148c..000000000000 --- a/internal/services/firewall/validate/firewall_id_test.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package validate - -// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten - -import "testing" - -func TestFirewallID(t *testing.T) { - cases := []struct { - Input string - Valid bool - }{ - - { - // empty - Input: "", - Valid: false, - }, - - { - // missing SubscriptionId - Input: "/", - Valid: false, - }, - - { - // missing value for SubscriptionId - Input: "/subscriptions/", - Valid: false, - }, - - { - // missing ResourceGroup - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/", - Valid: false, - }, - - { - // missing value for ResourceGroup - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/", - Valid: false, - }, - - { - // missing AzureFirewallName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/group1/providers/Microsoft.Network/", - Valid: false, - }, - - { - // missing value for AzureFirewallName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/group1/providers/Microsoft.Network/azureFirewalls/", - Valid: false, - }, - - { - // valid - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/group1/providers/Microsoft.Network/azureFirewalls/firewall1", - Valid: true, - }, - - { - // upper-cased - Input: "/SUBSCRIPTIONS/12345678-1234-9876-4563-123456789012/RESOURCEGROUPS/GROUP1/PROVIDERS/MICROSOFT.NETWORK/AZUREFIREWALLS/FIREWALL1", - Valid: false, - }, - } - for _, tc := range cases { - t.Logf("[DEBUG] Testing Value %s", tc.Input) - _, errors := FirewallID(tc.Input, "test") - valid := len(errors) == 0 - - if tc.Valid != valid { - t.Fatalf("Expected %t but got %t", tc.Valid, valid) - } - } -} diff --git a/internal/services/firewall/validate/firewall_policy_id.go b/internal/services/firewall/validate/firewall_policy_id.go deleted file mode 100644 index 3aff666bf0f2..000000000000 --- a/internal/services/firewall/validate/firewall_policy_id.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package validate - -// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten - -import ( - "fmt" - - "github.com/hashicorp/terraform-provider-azurerm/internal/services/firewall/parse" -) - -func FirewallPolicyID(input interface{}, key string) (warnings []string, errors []error) { - v, ok := input.(string) - if !ok { - errors = append(errors, fmt.Errorf("expected %q to be a string", key)) - return - } - - if _, err := parse.FirewallPolicyID(v); err != nil { - errors = append(errors, err) - } - - return -} diff --git a/internal/services/firewall/validate/firewall_policy_id_test.go b/internal/services/firewall/validate/firewall_policy_id_test.go deleted file mode 100644 index 9adc125881d7..000000000000 --- a/internal/services/firewall/validate/firewall_policy_id_test.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package validate - -// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten - -import "testing" - -func TestFirewallPolicyID(t *testing.T) { - cases := []struct { - Input string - Valid bool - }{ - - { - // empty - Input: "", - Valid: false, - }, - - { - // missing SubscriptionId - Input: "/", - Valid: false, - }, - - { - // missing value for SubscriptionId - Input: "/subscriptions/", - Valid: false, - }, - - { - // missing ResourceGroup - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/", - Valid: false, - }, - - { - // missing value for ResourceGroup - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/", - Valid: false, - }, - - { - // missing Name - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Network/", - Valid: false, - }, - - { - // missing value for Name - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Network/firewallPolicies/", - Valid: false, - }, - - { - // valid - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Network/firewallPolicies/policy1", - Valid: true, - }, - - { - // upper-cased - Input: "/SUBSCRIPTIONS/12345678-1234-9876-4563-123456789012/RESOURCEGROUPS/RESGROUP1/PROVIDERS/MICROSOFT.NETWORK/FIREWALLPOLICIES/POLICY1", - Valid: false, - }, - } - for _, tc := range cases { - t.Logf("[DEBUG] Testing Value %s", tc.Input) - _, errors := FirewallPolicyID(tc.Input, "test") - valid := len(errors) == 0 - - if tc.Valid != valid { - t.Fatalf("Expected %t but got %t", tc.Valid, valid) - } - } -} diff --git a/internal/services/firewall/validate/firewall_policy_rule_collection_group_id.go b/internal/services/firewall/validate/firewall_policy_rule_collection_group_id.go deleted file mode 100644 index b0e6217b1fd1..000000000000 --- a/internal/services/firewall/validate/firewall_policy_rule_collection_group_id.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package validate - -// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten - -import ( - "fmt" - - "github.com/hashicorp/terraform-provider-azurerm/internal/services/firewall/parse" -) - -func FirewallPolicyRuleCollectionGroupID(input interface{}, key string) (warnings []string, errors []error) { - v, ok := input.(string) - if !ok { - errors = append(errors, fmt.Errorf("expected %q to be a string", key)) - return - } - - if _, err := parse.FirewallPolicyRuleCollectionGroupID(v); err != nil { - errors = append(errors, err) - } - - return -} diff --git a/internal/services/firewall/validate/firewall_policy_rule_collection_group_id_test.go b/internal/services/firewall/validate/firewall_policy_rule_collection_group_id_test.go deleted file mode 100644 index 0cdd15ca70d3..000000000000 --- a/internal/services/firewall/validate/firewall_policy_rule_collection_group_id_test.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package validate - -// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten - -import "testing" - -func TestFirewallPolicyRuleCollectionGroupID(t *testing.T) { - cases := []struct { - Input string - Valid bool - }{ - - { - // empty - Input: "", - Valid: false, - }, - - { - // missing SubscriptionId - Input: "/", - Valid: false, - }, - - { - // missing value for SubscriptionId - Input: "/subscriptions/", - Valid: false, - }, - - { - // missing ResourceGroup - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/", - Valid: false, - }, - - { - // missing value for ResourceGroup - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/", - Valid: false, - }, - - { - // missing FirewallPolicyName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Network/", - Valid: false, - }, - - { - // missing value for FirewallPolicyName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Network/firewallPolicies/", - Valid: false, - }, - - { - // missing RuleCollectionGroupName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Network/firewallPolicies/policy1/", - Valid: false, - }, - - { - // missing value for RuleCollectionGroupName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Network/firewallPolicies/policy1/ruleCollectionGroups/", - Valid: false, - }, - - { - // valid - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Network/firewallPolicies/policy1/ruleCollectionGroups/ruleCollectionGroup1", - Valid: true, - }, - - { - // upper-cased - Input: "/SUBSCRIPTIONS/12345678-1234-9876-4563-123456789012/RESOURCEGROUPS/RESGROUP1/PROVIDERS/MICROSOFT.NETWORK/FIREWALLPOLICIES/POLICY1/RULECOLLECTIONGROUPS/RULECOLLECTIONGROUP1", - Valid: false, - }, - } - for _, tc := range cases { - t.Logf("[DEBUG] Testing Value %s", tc.Input) - _, errors := FirewallPolicyRuleCollectionGroupID(tc.Input, "test") - valid := len(errors) == 0 - - if tc.Valid != valid { - t.Fatalf("Expected %t but got %t", tc.Valid, valid) - } - } -} diff --git a/internal/services/network/ip_group_resource.go b/internal/services/network/ip_group_resource.go index 1ca2ef7bd49b..1cfc06ea1c02 100644 --- a/internal/services/network/ip_group_resource.go +++ b/internal/services/network/ip_group_resource.go @@ -9,12 +9,13 @@ import ( "time" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" + "github.com/hashicorp/go-azure-sdk/resource-manager/network/2023-04-01/azurefirewalls" + "github.com/hashicorp/go-azure-sdk/resource-manager/network/2023-04-01/firewallpolicies" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/locks" "github.com/hashicorp/terraform-provider-azurerm/internal/services/firewall" - firewallParse "github.com/hashicorp/terraform-provider-azurerm/internal/services/firewall/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/network/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" @@ -92,15 +93,15 @@ func resourceIpGroupCreate(d *pluginsdk.ResourceData, meta interface{}) error { defer cancel() for _, fw := range d.Get("firewall_ids").([]interface{}) { - id, _ := firewallParse.FirewallID(fw.(string)) + id, _ := azurefirewalls.ParseAzureFirewallID(fw.(string)) locks.ByName(id.AzureFirewallName, firewall.AzureFirewallResourceName) defer locks.UnlockByName(id.AzureFirewallName, firewall.AzureFirewallResourceName) } for _, fwpol := range d.Get("firewall_policy_ids").([]interface{}) { - id, _ := firewallParse.FirewallPolicyID(fwpol.(string)) - locks.ByName(id.Name, firewall.AzureFirewallPolicyResourceName) - defer locks.UnlockByName(id.Name, firewall.AzureFirewallPolicyResourceName) + id, _ := firewallpolicies.ParseFirewallPolicyID(fwpol.(string)) + locks.ByName(id.FirewallPolicyName, firewall.AzureFirewallPolicyResourceName) + defer locks.UnlockByName(id.FirewallPolicyName, firewall.AzureFirewallPolicyResourceName) } id := parse.NewIpGroupID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) @@ -195,15 +196,15 @@ func resourceIpGroupUpdate(d *pluginsdk.ResourceData, meta interface{}) error { defer cancel() for _, fw := range d.Get("firewall_ids").([]interface{}) { - id, _ := firewallParse.FirewallID(fw.(string)) + id, _ := azurefirewalls.ParseAzureFirewallID(fw.(string)) locks.ByName(id.AzureFirewallName, firewall.AzureFirewallResourceName) defer locks.UnlockByName(id.AzureFirewallName, firewall.AzureFirewallResourceName) } for _, fwpol := range d.Get("firewall_policy_ids").([]interface{}) { - id, _ := firewallParse.FirewallPolicyID(fwpol.(string)) - locks.ByName(id.Name, firewall.AzureFirewallPolicyResourceName) - defer locks.UnlockByName(id.Name, firewall.AzureFirewallPolicyResourceName) + id, _ := firewallpolicies.ParseFirewallPolicyID(fwpol.(string)) + locks.ByName(id.FirewallPolicyName, firewall.AzureFirewallPolicyResourceName) + defer locks.UnlockByName(id.FirewallPolicyName, firewall.AzureFirewallPolicyResourceName) } id := parse.NewIpGroupID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) @@ -286,15 +287,15 @@ func resourceIpGroupDelete(d *pluginsdk.ResourceData, meta interface{}) error { } for _, fw := range *read.Firewalls { - id, _ := firewallParse.FirewallID(*fw.ID) + id, _ := azurefirewalls.ParseAzureFirewallID(*fw.ID) locks.ByName(id.AzureFirewallName, firewall.AzureFirewallResourceName) defer locks.UnlockByName(id.AzureFirewallName, firewall.AzureFirewallResourceName) } for _, fwpol := range *read.FirewallPolicies { - id, _ := firewallParse.FirewallPolicyID(*fwpol.ID) - locks.ByName(id.Name, firewall.AzureFirewallPolicyResourceName) - defer locks.UnlockByName(id.Name, firewall.AzureFirewallPolicyResourceName) + id, _ := firewallpolicies.ParseFirewallPolicyID(*fwpol.ID) + locks.ByName(id.FirewallPolicyName, firewall.AzureFirewallPolicyResourceName) + defer locks.UnlockByName(id.FirewallPolicyName, firewall.AzureFirewallPolicyResourceName) } future, err := client.Delete(ctx, id.ResourceGroup, id.Name)