Skip to content

Commit

Permalink
Merge pull request #8172 from terraform-providers/refactor/load-balan…
Browse files Browse the repository at this point in the history
…cers

refactor: cleaning up load balancers & adding validation to Load Balancer ID's & at import time
  • Loading branch information
tombuildsstuff authored Aug 20, 2020
2 parents 22f8617 + 9abb3bb commit bd9b4cd
Show file tree
Hide file tree
Showing 28 changed files with 1,439 additions and 381 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@ import (

"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/network/parse"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/network/validate"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts"
)

func dataSourceArmLoadBalancerBackendAddressPool() *schema.Resource {
return &schema.Resource{
Read: dataSourceArmLoadBalancerBackendAddressPoolRead,

Timeouts: &schema.ResourceTimeout{
Read: schema.DefaultTimeout(5 * time.Minute),
},
Expand All @@ -27,7 +29,7 @@ func dataSourceArmLoadBalancerBackendAddressPool() *schema.Resource {
"loadbalancer_id": {
Type: schema.TypeString,
Required: true,
ValidateFunc: azure.ValidateResourceID,
ValidateFunc: validate.LoadBalancerID,
},

"backend_ip_configurations": {
Expand All @@ -47,20 +49,27 @@ func dataSourceArmLoadBalancerBackendAddressPool() *schema.Resource {
}

func dataSourceArmLoadBalancerBackendAddressPoolRead(d *schema.ResourceData, meta interface{}) error {
loadBalancerID := d.Get("loadbalancer_id").(string)
client := meta.(*clients.Client).Network.LoadBalancersClient
ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
defer cancel()

name := d.Get("name").(string)
loadBalancerId, err := parse.LoadBalancerID(d.Get("loadbalancer_id").(string))
if err != nil {
return err
}

loadBalancer, exists, err := retrieveLoadBalancerById(d, d.Get("loadbalancer_id").(string), meta)
loadBalancer, exists, err := retrieveLoadBalancerById(ctx, client, *loadBalancerId)
if err != nil {
return fmt.Errorf("Error retrieving Load Balancer by ID: %+v", err)
return fmt.Errorf("retrieving Load Balancer by ID: %+v", err)
}
if !exists {
return fmt.Errorf("Unable to retrieve Backend Address Pool %q since Load Balancer %q was not found", name, loadBalancerID)
return fmt.Errorf("Load Balancer %q (Resource Group %q) was not found", loadBalancerId.Name, loadBalancerId.ResourceGroup)
}

bap, _, exists := FindLoadBalancerBackEndAddressPoolByName(loadBalancer, name)
if !exists {
return fmt.Errorf("Backend Address Pool %q was not found in Load Balancer %q", name, loadBalancerID)
return fmt.Errorf("Backend Address Pool %q was not found in Load Balancer %q (Resource Group %q)", name, loadBalancerId.Name, loadBalancerId.ResourceGroup)
}

d.SetId(*bap.ID)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import (
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/locks"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/network/parse"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/network/validate"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)
Expand All @@ -22,9 +24,16 @@ func resourceArmLoadBalancerBackendAddressPool() *schema.Resource {
Create: resourceArmLoadBalancerBackendAddressPoolCreate,
Read: resourceArmLoadBalancerBackendAddressPoolRead,
Delete: resourceArmLoadBalancerBackendAddressPoolDelete,
Importer: &schema.ResourceImporter{
State: loadBalancerSubResourceStateImporter,
},

Importer: loadBalancerSubResourceImporter(func(input string) (*parse.LoadBalancerId, error) {
id, err := parse.LoadBalancerBackendAddressPoolID(input)
if err != nil {
return nil, err
}

lbId := parse.NewLoadBalancerID(id.ResourceGroup, id.LoadBalancerName)
return &lbId, nil
}),

Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(30 * time.Minute),
Expand All @@ -47,7 +56,7 @@ func resourceArmLoadBalancerBackendAddressPool() *schema.Resource {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: azure.ValidateResourceID,
ValidateFunc: validate.LoadBalancerID,
},

"backend_ip_configurations": {
Expand Down Expand Up @@ -75,15 +84,21 @@ func resourceArmLoadBalancerBackendAddressPool() *schema.Resource {

func resourceArmLoadBalancerBackendAddressPoolCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Network.LoadBalancersClient
subscriptionId := meta.(*clients.Client).Account.SubscriptionId
ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d)
defer cancel()

loadBalancerID := d.Get("loadbalancer_id").(string)
name := d.Get("name").(string)
loadBalancerId, err := parse.LoadBalancerID(d.Get("loadbalancer_id").(string))
if err != nil {
return fmt.Errorf("parsing Load Balancer Name and Group: %+v", err)
}

loadBalancerID := loadBalancerId.ID(subscriptionId)
locks.ByID(loadBalancerID)
defer locks.UnlockByID(loadBalancerID)

loadBalancer, exists, err := retrieveLoadBalancerById(d, loadBalancerID, meta)
loadBalancer, exists, err := retrieveLoadBalancerById(ctx, client, *loadBalancerId)
if err != nil {
return fmt.Errorf("Error Getting Load Balancer By ID: %+v", err)
}
Expand All @@ -93,7 +108,9 @@ func resourceArmLoadBalancerBackendAddressPoolCreate(d *schema.ResourceData, met
return nil
}

backendAddressPools := append(*loadBalancer.LoadBalancerPropertiesFormat.BackendAddressPools, expandAzureRmLoadBalancerBackendAddressPools(d))
backendAddressPools := append(*loadBalancer.LoadBalancerPropertiesFormat.BackendAddressPools, network.BackendAddressPool{
Name: utils.String(name),
})
existingPool, existingPoolIndex, exists := FindLoadBalancerBackEndAddressPoolByName(loadBalancer, name)
if exists {
if name == *existingPool.Name {
Expand All @@ -107,26 +124,22 @@ func resourceArmLoadBalancerBackendAddressPoolCreate(d *schema.ResourceData, met
}

loadBalancer.LoadBalancerPropertiesFormat.BackendAddressPools = &backendAddressPools
resGroup, loadBalancerName, err := resourceGroupAndLBNameFromId(d.Get("loadbalancer_id").(string))
if err != nil {
return fmt.Errorf("Error parsing Load Balancer Name and Group: %+v", err)
}

future, err := client.CreateOrUpdate(ctx, resGroup, loadBalancerName, *loadBalancer)
future, err := client.CreateOrUpdate(ctx, loadBalancerId.ResourceGroup, loadBalancerId.Name, *loadBalancer)
if err != nil {
return fmt.Errorf("Error Creating/Updating Load Balancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err)
return fmt.Errorf("Error Creating/Updating Load Balancer %q (Resource Group %q): %+v", loadBalancerId.Name, loadBalancerId.ResourceGroup, err)
}

if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("Error Creating/Updating Load Balancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err)
return fmt.Errorf("Error Creating/Updating Load Balancer %q (Resource Group %q): %+v", loadBalancerId.Name, loadBalancerId.ResourceGroup, err)
}

read, err := client.Get(ctx, resGroup, loadBalancerName, "")
read, err := client.Get(ctx, loadBalancerId.ResourceGroup, loadBalancerId.Name, "")
if err != nil {
return fmt.Errorf("Error retrieving Load Balancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err)
return fmt.Errorf("retrieving Load Balancer %q (Resource Group %q): %+v", loadBalancerId.Name, loadBalancerId.ResourceGroup, err)
}
if read.ID == nil {
return fmt.Errorf("Cannot read Load Balancer %q (Resource Group %q) ID", loadBalancerName, resGroup)
return fmt.Errorf("reading ID for Load Balancer %q (Resource Group %q)", loadBalancerId.Name, loadBalancerId.ResourceGroup)
}

var poolId string
Expand All @@ -146,26 +159,30 @@ func resourceArmLoadBalancerBackendAddressPoolCreate(d *schema.ResourceData, met
}

func resourceArmLoadBalancerBackendAddressPoolRead(d *schema.ResourceData, meta interface{}) error {
id, err := azure.ParseAzureResourceID(d.Id())
client := meta.(*clients.Client).Network.LoadBalancersClient
ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
defer cancel()

id, err := parse.LoadBalancerBackendAddressPoolID(d.Id())
if err != nil {
return err
}
name := id.Path["backendAddressPools"]

loadBalancer, exists, err := retrieveLoadBalancerById(d, d.Get("loadbalancer_id").(string), meta)
loadBalancerId := parse.NewLoadBalancerID(id.ResourceGroup, id.LoadBalancerName)
loadBalancer, exists, err := retrieveLoadBalancerById(ctx, client, loadBalancerId)
if err != nil {
return fmt.Errorf("Error retrieving Load Balancer by ID: %+v", err)
return fmt.Errorf("retrieving Load Balancer by ID: %+v", err)
}
if !exists {
d.SetId("")
log.Printf("[INFO] Load Balancer %q not found. Removing from state", name)
log.Printf("[INFO] Load Balancer %q not found. Removing from state", id.LoadBalancerName)
return nil
}

config, _, exists := FindLoadBalancerBackEndAddressPoolByName(loadBalancer, name)
config, _, exists := FindLoadBalancerBackEndAddressPoolByName(loadBalancer, id.Name)
if !exists {
log.Printf("[INFO] Load Balancer Backend Address Pool %q not found. Removing from state", id.Name)
d.SetId("")
log.Printf("[INFO] Load Balancer Backend Address Pool %q not found. Removing from state", name)
return nil
}

Expand Down Expand Up @@ -197,14 +214,21 @@ func resourceArmLoadBalancerBackendAddressPoolRead(d *schema.ResourceData, meta

func resourceArmLoadBalancerBackendAddressPoolDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Network.LoadBalancersClient
subscriptionId := meta.(*clients.Client).Account.SubscriptionId
ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d)
defer cancel()

loadBalancerID := d.Get("loadbalancer_id").(string)
id, err := parse.LoadBalancerBackendAddressPoolID(d.Id())
if err != nil {
return err
}

loadBalancerId := parse.NewLoadBalancerID(id.ResourceGroup, id.LoadBalancerName)
loadBalancerID := loadBalancerId.ID(subscriptionId)
locks.ByID(loadBalancerID)
defer locks.UnlockByID(loadBalancerID)

loadBalancer, exists, err := retrieveLoadBalancerById(d, loadBalancerID, meta)
loadBalancer, exists, err := retrieveLoadBalancerById(ctx, client, loadBalancerId)
if err != nil {
return fmt.Errorf("Error retrieving Load Balancer by ID: %+v", err)
}
Expand All @@ -222,12 +246,7 @@ func resourceArmLoadBalancerBackendAddressPoolDelete(d *schema.ResourceData, met
newBackEndPools := append(oldBackEndPools[:index], oldBackEndPools[index+1:]...)
loadBalancer.LoadBalancerPropertiesFormat.BackendAddressPools = &newBackEndPools

resGroup, loadBalancerName, err := resourceGroupAndLBNameFromId(d.Get("loadbalancer_id").(string))
if err != nil {
return fmt.Errorf("Error Getting Load Balancer Name and Group:: %+v", err)
}

future, err := client.CreateOrUpdate(ctx, resGroup, loadBalancerName, *loadBalancer)
future, err := client.CreateOrUpdate(ctx, id.ResourceGroup, id.LoadBalancerName, *loadBalancer)
if err != nil {
return fmt.Errorf("Error Creating/Updating LoadBalancer: %+v", err)
}
Expand All @@ -236,19 +255,13 @@ func resourceArmLoadBalancerBackendAddressPoolDelete(d *schema.ResourceData, met
return fmt.Errorf("Error waiting for the completion for the LoadBalancer: %+v", err)
}

read, err := client.Get(ctx, resGroup, loadBalancerName, "")
read, err := client.Get(ctx, id.ResourceGroup, id.LoadBalancerName, "")
if err != nil {
return fmt.Errorf("Error retrieving the Load Balancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err)
return fmt.Errorf("Error retrieving the Load Balancer %q (Resource Group %q): %+v", id.LoadBalancerName, id.ResourceGroup, err)
}
if read.ID == nil {
return fmt.Errorf("Cannot read Load Balancer %q (resource group %q) ID", loadBalancerName, resGroup)
return fmt.Errorf("Cannot read Load Balancer %q (resource group %q) ID", id.LoadBalancerName, id.ResourceGroup)
}

return nil
}

func expandAzureRmLoadBalancerBackendAddressPools(d *schema.ResourceData) network.BackendAddressPool {
return network.BackendAddressPool{
Name: utils.String(d.Get("name").(string)),
}
}
6 changes: 3 additions & 3 deletions azurerm/internal/services/network/lb_data_source.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,13 +102,13 @@ func dataSourceArmLoadBalancer() *schema.Resource {
}

func dataSourceArmLoadBalancerRead(d *schema.ResourceData, meta interface{}) error {
name := d.Get("name").(string)
resourceGroup := d.Get("resource_group_name").(string)

client := meta.(*clients.Client).Network.LoadBalancersClient
ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
defer cancel()

name := d.Get("name").(string)
resourceGroup := d.Get("resource_group_name").(string)

resp, err := client.Get(ctx, resourceGroup, name, "")
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
Expand Down
Loading

0 comments on commit bd9b4cd

Please sign in to comment.