github.com/danp/terraform@v0.9.5-0.20170426144147-39d740081351/builtin/providers/azurerm/resource_arm_loadbalancer_backend_address_pool.go (about)

     1  package azurerm
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"time"
     7  
     8  	"github.com/Azure/azure-sdk-for-go/arm/network"
     9  	"github.com/hashicorp/errwrap"
    10  	"github.com/hashicorp/terraform/helper/resource"
    11  	"github.com/hashicorp/terraform/helper/schema"
    12  	"github.com/jen20/riviera/azure"
    13  )
    14  
    15  func resourceArmLoadBalancerBackendAddressPool() *schema.Resource {
    16  	return &schema.Resource{
    17  		Create: resourceArmLoadBalancerBackendAddressPoolCreate,
    18  		Read:   resourceArmLoadBalancerBackendAddressPoolRead,
    19  		Delete: resourceArmLoadBalancerBackendAddressPoolDelete,
    20  		Importer: &schema.ResourceImporter{
    21  			State: loadBalancerSubResourceStateImporter,
    22  		},
    23  
    24  		Schema: map[string]*schema.Schema{
    25  			"name": {
    26  				Type:     schema.TypeString,
    27  				Required: true,
    28  				ForceNew: true,
    29  			},
    30  
    31  			"location": {
    32  				Type:             schema.TypeString,
    33  				ForceNew:         true,
    34  				Optional:         true,
    35  				StateFunc:        azureRMNormalizeLocation,
    36  				DiffSuppressFunc: azureRMSuppressLocationDiff,
    37  				Deprecated:       "location is no longer used",
    38  			},
    39  
    40  			"resource_group_name": {
    41  				Type:     schema.TypeString,
    42  				Required: true,
    43  				ForceNew: true,
    44  			},
    45  
    46  			"loadbalancer_id": {
    47  				Type:     schema.TypeString,
    48  				Required: true,
    49  				ForceNew: true,
    50  			},
    51  
    52  			"backend_ip_configurations": {
    53  				Type:     schema.TypeSet,
    54  				Computed: true,
    55  				Elem:     &schema.Schema{Type: schema.TypeString},
    56  				Set:      schema.HashString,
    57  			},
    58  
    59  			"load_balancing_rules": {
    60  				Type:     schema.TypeSet,
    61  				Computed: true,
    62  				Elem:     &schema.Schema{Type: schema.TypeString},
    63  				Set:      schema.HashString,
    64  			},
    65  		},
    66  	}
    67  }
    68  
    69  func resourceArmLoadBalancerBackendAddressPoolCreate(d *schema.ResourceData, meta interface{}) error {
    70  	client := meta.(*ArmClient)
    71  	lbClient := client.loadBalancerClient
    72  
    73  	loadBalancerID := d.Get("loadbalancer_id").(string)
    74  	armMutexKV.Lock(loadBalancerID)
    75  	defer armMutexKV.Unlock(loadBalancerID)
    76  
    77  	loadBalancer, exists, err := retrieveLoadBalancerById(loadBalancerID, meta)
    78  	if err != nil {
    79  		return errwrap.Wrapf("Error Getting LoadBalancer By ID {{err}}", err)
    80  	}
    81  	if !exists {
    82  		d.SetId("")
    83  		log.Printf("[INFO] LoadBalancer %q not found. Removing from state", d.Get("name").(string))
    84  		return nil
    85  	}
    86  
    87  	backendAddressPools := append(*loadBalancer.LoadBalancerPropertiesFormat.BackendAddressPools, expandAzureRmLoadBalancerBackendAddressPools(d))
    88  	existingPool, existingPoolIndex, exists := findLoadBalancerBackEndAddressPoolByName(loadBalancer, d.Get("name").(string))
    89  	if exists {
    90  		if d.Get("name").(string) == *existingPool.Name {
    91  			// this pool is being updated/reapplied remove old copy from the slice
    92  			backendAddressPools = append(backendAddressPools[:existingPoolIndex], backendAddressPools[existingPoolIndex+1:]...)
    93  		}
    94  	}
    95  
    96  	loadBalancer.LoadBalancerPropertiesFormat.BackendAddressPools = &backendAddressPools
    97  	resGroup, loadBalancerName, err := resourceGroupAndLBNameFromId(d.Get("loadbalancer_id").(string))
    98  	if err != nil {
    99  		return errwrap.Wrapf("Error Getting LoadBalancer Name and Group: {{err}}", err)
   100  	}
   101  
   102  	_, err = lbClient.CreateOrUpdate(resGroup, loadBalancerName, *loadBalancer, make(chan struct{}))
   103  	if err != nil {
   104  		return errwrap.Wrapf("Error Creating/Updating LoadBalancer {{err}}", err)
   105  	}
   106  
   107  	read, err := lbClient.Get(resGroup, loadBalancerName, "")
   108  	if err != nil {
   109  		return errwrap.Wrapf("Error Getting LoadBalancer {{err}}", err)
   110  	}
   111  	if read.ID == nil {
   112  		return fmt.Errorf("Cannot read LoadBalancer %s (resource group %s) ID", loadBalancerName, resGroup)
   113  	}
   114  
   115  	var pool_id string
   116  	for _, BackendAddressPool := range *(*read.LoadBalancerPropertiesFormat).BackendAddressPools {
   117  		if *BackendAddressPool.Name == d.Get("name").(string) {
   118  			pool_id = *BackendAddressPool.ID
   119  		}
   120  	}
   121  
   122  	if pool_id != "" {
   123  		d.SetId(pool_id)
   124  	} else {
   125  		return fmt.Errorf("Cannot find created LoadBalancer Backend Address Pool ID %q", pool_id)
   126  	}
   127  
   128  	log.Printf("[DEBUG] Waiting for LoadBalancer (%s) to become available", loadBalancerName)
   129  	stateConf := &resource.StateChangeConf{
   130  		Pending: []string{"Accepted", "Updating"},
   131  		Target:  []string{"Succeeded"},
   132  		Refresh: loadbalancerStateRefreshFunc(client, resGroup, loadBalancerName),
   133  		Timeout: 10 * time.Minute,
   134  	}
   135  	if _, err := stateConf.WaitForState(); err != nil {
   136  		return fmt.Errorf("Error waiting for LoadBalancer (%s) to become available: %s", loadBalancerName, err)
   137  	}
   138  
   139  	return resourceArmLoadBalancerBackendAddressPoolRead(d, meta)
   140  }
   141  
   142  func resourceArmLoadBalancerBackendAddressPoolRead(d *schema.ResourceData, meta interface{}) error {
   143  	id, err := parseAzureResourceID(d.Id())
   144  	if err != nil {
   145  		return err
   146  	}
   147  	name := id.Path["backendAddressPools"]
   148  
   149  	loadBalancer, exists, err := retrieveLoadBalancerById(d.Get("loadbalancer_id").(string), meta)
   150  	if err != nil {
   151  		return errwrap.Wrapf("Error Getting LoadBalancer By ID {{err}}", err)
   152  	}
   153  	if !exists {
   154  		d.SetId("")
   155  		log.Printf("[INFO] LoadBalancer %q not found. Removing from state", name)
   156  		return nil
   157  	}
   158  
   159  	config, _, exists := findLoadBalancerBackEndAddressPoolByName(loadBalancer, name)
   160  	if !exists {
   161  		d.SetId("")
   162  		log.Printf("[INFO] LoadBalancer Backend Address Pool %q not found. Removing from state", name)
   163  		return nil
   164  	}
   165  
   166  	d.Set("name", config.Name)
   167  	d.Set("resource_group_name", id.ResourceGroup)
   168  
   169  	var backend_ip_configurations []string
   170  	if config.BackendAddressPoolPropertiesFormat.BackendIPConfigurations != nil {
   171  		for _, backendConfig := range *config.BackendAddressPoolPropertiesFormat.BackendIPConfigurations {
   172  			backend_ip_configurations = append(backend_ip_configurations, *backendConfig.ID)
   173  		}
   174  
   175  	}
   176  	d.Set("backend_ip_configurations", backend_ip_configurations)
   177  
   178  	var load_balancing_rules []string
   179  	if config.BackendAddressPoolPropertiesFormat.LoadBalancingRules != nil {
   180  		for _, rule := range *config.BackendAddressPoolPropertiesFormat.LoadBalancingRules {
   181  			load_balancing_rules = append(load_balancing_rules, *rule.ID)
   182  		}
   183  	}
   184  	d.Set("load_balancing_rules", load_balancing_rules)
   185  
   186  	return nil
   187  }
   188  
   189  func resourceArmLoadBalancerBackendAddressPoolDelete(d *schema.ResourceData, meta interface{}) error {
   190  	client := meta.(*ArmClient)
   191  	lbClient := client.loadBalancerClient
   192  
   193  	loadBalancerID := d.Get("loadbalancer_id").(string)
   194  	armMutexKV.Lock(loadBalancerID)
   195  	defer armMutexKV.Unlock(loadBalancerID)
   196  
   197  	loadBalancer, exists, err := retrieveLoadBalancerById(loadBalancerID, meta)
   198  	if err != nil {
   199  		return errwrap.Wrapf("Error Getting LoadBalancer By ID {{err}}", err)
   200  	}
   201  	if !exists {
   202  		d.SetId("")
   203  		return nil
   204  	}
   205  
   206  	_, index, exists := findLoadBalancerBackEndAddressPoolByName(loadBalancer, d.Get("name").(string))
   207  	if !exists {
   208  		return nil
   209  	}
   210  
   211  	oldBackEndPools := *loadBalancer.LoadBalancerPropertiesFormat.BackendAddressPools
   212  	newBackEndPools := append(oldBackEndPools[:index], oldBackEndPools[index+1:]...)
   213  	loadBalancer.LoadBalancerPropertiesFormat.BackendAddressPools = &newBackEndPools
   214  
   215  	resGroup, loadBalancerName, err := resourceGroupAndLBNameFromId(d.Get("loadbalancer_id").(string))
   216  	if err != nil {
   217  		return errwrap.Wrapf("Error Getting LoadBalancer Name and Group: {{err}}", err)
   218  	}
   219  
   220  	_, err = lbClient.CreateOrUpdate(resGroup, loadBalancerName, *loadBalancer, make(chan struct{}))
   221  	if err != nil {
   222  		return errwrap.Wrapf("Error Creating/Updating LoadBalancer {{err}}", err)
   223  	}
   224  
   225  	read, err := lbClient.Get(resGroup, loadBalancerName, "")
   226  	if err != nil {
   227  		return errwrap.Wrapf("Error Getting LoadBalancer {{err}}", err)
   228  	}
   229  	if read.ID == nil {
   230  		return fmt.Errorf("Cannot read LoadBalancer %s (resource group %s) ID", loadBalancerName, resGroup)
   231  	}
   232  
   233  	return nil
   234  }
   235  
   236  func expandAzureRmLoadBalancerBackendAddressPools(d *schema.ResourceData) network.BackendAddressPool {
   237  	return network.BackendAddressPool{
   238  		Name: azure.String(d.Get("name").(string)),
   239  	}
   240  }