github.com/aspring/terraform@v0.8.2-0.20161216122603-6a8619a5db2e/builtin/providers/azurerm/resource_arm_loadbalancer_rule.go (about)

     1  package azurerm
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"regexp"
     7  	"time"
     8  
     9  	"github.com/Azure/azure-sdk-for-go/arm/network"
    10  	"github.com/hashicorp/errwrap"
    11  	"github.com/hashicorp/terraform/helper/resource"
    12  	"github.com/hashicorp/terraform/helper/schema"
    13  	"github.com/jen20/riviera/azure"
    14  )
    15  
    16  func resourceArmLoadBalancerRule() *schema.Resource {
    17  	return &schema.Resource{
    18  		Create: resourceArmLoadBalancerRuleCreate,
    19  		Read:   resourceArmLoadBalancerRuleRead,
    20  		Update: resourceArmLoadBalancerRuleCreate,
    21  		Delete: resourceArmLoadBalancerRuleDelete,
    22  
    23  		Schema: map[string]*schema.Schema{
    24  			"name": {
    25  				Type:         schema.TypeString,
    26  				Required:     true,
    27  				ForceNew:     true,
    28  				ValidateFunc: validateArmLoadBalancerRuleName,
    29  			},
    30  
    31  			"location": locationSchema(),
    32  
    33  			"resource_group_name": {
    34  				Type:     schema.TypeString,
    35  				Required: true,
    36  				ForceNew: true,
    37  			},
    38  
    39  			"loadbalancer_id": {
    40  				Type:     schema.TypeString,
    41  				Required: true,
    42  				ForceNew: true,
    43  			},
    44  
    45  			"frontend_ip_configuration_name": {
    46  				Type:     schema.TypeString,
    47  				Required: true,
    48  			},
    49  
    50  			"frontend_ip_configuration_id": {
    51  				Type:     schema.TypeString,
    52  				Computed: true,
    53  			},
    54  
    55  			"backend_address_pool_id": {
    56  				Type:     schema.TypeString,
    57  				Optional: true,
    58  				Computed: true,
    59  			},
    60  
    61  			"protocol": {
    62  				Type:     schema.TypeString,
    63  				Required: true,
    64  			},
    65  
    66  			"frontend_port": {
    67  				Type:     schema.TypeInt,
    68  				Required: true,
    69  			},
    70  
    71  			"backend_port": {
    72  				Type:     schema.TypeInt,
    73  				Required: true,
    74  			},
    75  
    76  			"probe_id": {
    77  				Type:     schema.TypeString,
    78  				Optional: true,
    79  				Computed: true,
    80  			},
    81  
    82  			"enable_floating_ip": {
    83  				Type:     schema.TypeBool,
    84  				Optional: true,
    85  				Default:  false,
    86  			},
    87  
    88  			"idle_timeout_in_minutes": {
    89  				Type:     schema.TypeInt,
    90  				Optional: true,
    91  				Computed: true,
    92  			},
    93  
    94  			"load_distribution": {
    95  				Type:     schema.TypeString,
    96  				Optional: true,
    97  				Computed: true,
    98  			},
    99  		},
   100  	}
   101  }
   102  
   103  func resourceArmLoadBalancerRuleCreate(d *schema.ResourceData, meta interface{}) error {
   104  	client := meta.(*ArmClient)
   105  	lbClient := client.loadBalancerClient
   106  
   107  	loadBalancerID := d.Get("loadbalancer_id").(string)
   108  	armMutexKV.Lock(loadBalancerID)
   109  	defer armMutexKV.Unlock(loadBalancerID)
   110  
   111  	loadBalancer, exists, err := retrieveLoadBalancerById(loadBalancerID, meta)
   112  	if err != nil {
   113  		return errwrap.Wrapf("Error Getting LoadBalancer By ID {{err}}", err)
   114  	}
   115  	if !exists {
   116  		d.SetId("")
   117  		log.Printf("[INFO] LoadBalancer %q not found. Removing from state", d.Get("name").(string))
   118  		return nil
   119  	}
   120  
   121  	newLbRule, err := expandAzureRmLoadBalancerRule(d, loadBalancer)
   122  	if err != nil {
   123  		return errwrap.Wrapf("Error Exanding LoadBalancer Rule {{err}}", err)
   124  	}
   125  
   126  	lbRules := append(*loadBalancer.LoadBalancerPropertiesFormat.LoadBalancingRules, *newLbRule)
   127  
   128  	existingRule, existingRuleIndex, exists := findLoadBalancerRuleByName(loadBalancer, d.Get("name").(string))
   129  	if exists {
   130  		if d.Id() == *existingRule.ID {
   131  			// this rule is being updated remove old copy from the slice
   132  			lbRules = append(lbRules[:existingRuleIndex], lbRules[existingRuleIndex+1:]...)
   133  		} else {
   134  			return fmt.Errorf("A LoadBalancer Rule with name %q already exists.", d.Get("name").(string))
   135  		}
   136  	}
   137  
   138  	loadBalancer.LoadBalancerPropertiesFormat.LoadBalancingRules = &lbRules
   139  	resGroup, loadBalancerName, err := resourceGroupAndLBNameFromId(d.Get("loadbalancer_id").(string))
   140  	if err != nil {
   141  		return errwrap.Wrapf("Error Getting LoadBalancer Name and Group: {{err}}", err)
   142  	}
   143  
   144  	_, err = lbClient.CreateOrUpdate(resGroup, loadBalancerName, *loadBalancer, make(chan struct{}))
   145  	if err != nil {
   146  		return errwrap.Wrapf("Error Creating/Updating LoadBalancer {{err}}", err)
   147  	}
   148  
   149  	read, err := lbClient.Get(resGroup, loadBalancerName, "")
   150  	if err != nil {
   151  		return errwrap.Wrapf("Error Getting LoadBalancer {{err}}", err)
   152  	}
   153  	if read.ID == nil {
   154  		return fmt.Errorf("Cannot read LoadBalancer %s (resource group %s) ID", loadBalancerName, resGroup)
   155  	}
   156  
   157  	var rule_id string
   158  	for _, LoadBalancingRule := range *(*read.LoadBalancerPropertiesFormat).LoadBalancingRules {
   159  		if *LoadBalancingRule.Name == d.Get("name").(string) {
   160  			rule_id = *LoadBalancingRule.ID
   161  		}
   162  	}
   163  
   164  	if rule_id != "" {
   165  		d.SetId(rule_id)
   166  	} else {
   167  		return fmt.Errorf("Cannot find created LoadBalancer Rule ID %q", rule_id)
   168  	}
   169  
   170  	log.Printf("[DEBUG] Waiting for LoadBalancer (%s) to become available", loadBalancerName)
   171  	stateConf := &resource.StateChangeConf{
   172  		Pending: []string{"Accepted", "Updating"},
   173  		Target:  []string{"Succeeded"},
   174  		Refresh: loadbalancerStateRefreshFunc(client, resGroup, loadBalancerName),
   175  		Timeout: 10 * time.Minute,
   176  	}
   177  	if _, err := stateConf.WaitForState(); err != nil {
   178  		return fmt.Errorf("Error waiting for LoadBalancer (%s) to become available: %s", loadBalancerName, err)
   179  	}
   180  
   181  	return resourceArmLoadBalancerRuleRead(d, meta)
   182  }
   183  
   184  func resourceArmLoadBalancerRuleRead(d *schema.ResourceData, meta interface{}) error {
   185  	loadBalancer, exists, err := retrieveLoadBalancerById(d.Get("loadbalancer_id").(string), meta)
   186  	if err != nil {
   187  		return errwrap.Wrapf("Error Getting LoadBalancer By ID {{err}}", err)
   188  	}
   189  	if !exists {
   190  		d.SetId("")
   191  		log.Printf("[INFO] LoadBalancer %q not found. Removing from state", d.Get("name").(string))
   192  		return nil
   193  	}
   194  
   195  	configs := *loadBalancer.LoadBalancerPropertiesFormat.LoadBalancingRules
   196  	for _, config := range configs {
   197  		if *config.Name == d.Get("name").(string) {
   198  			d.Set("name", config.Name)
   199  
   200  			d.Set("protocol", config.LoadBalancingRulePropertiesFormat.Protocol)
   201  			d.Set("frontend_port", config.LoadBalancingRulePropertiesFormat.FrontendPort)
   202  			d.Set("backend_port", config.LoadBalancingRulePropertiesFormat.BackendPort)
   203  
   204  			if config.LoadBalancingRulePropertiesFormat.EnableFloatingIP != nil {
   205  				d.Set("enable_floating_ip", config.LoadBalancingRulePropertiesFormat.EnableFloatingIP)
   206  			}
   207  
   208  			if config.LoadBalancingRulePropertiesFormat.IdleTimeoutInMinutes != nil {
   209  				d.Set("idle_timeout_in_minutes", config.LoadBalancingRulePropertiesFormat.IdleTimeoutInMinutes)
   210  			}
   211  
   212  			if config.LoadBalancingRulePropertiesFormat.FrontendIPConfiguration != nil {
   213  				d.Set("frontend_ip_configuration_id", config.LoadBalancingRulePropertiesFormat.FrontendIPConfiguration.ID)
   214  			}
   215  
   216  			if config.LoadBalancingRulePropertiesFormat.BackendAddressPool != nil {
   217  				d.Set("backend_address_pool_id", config.LoadBalancingRulePropertiesFormat.BackendAddressPool.ID)
   218  			}
   219  
   220  			if config.LoadBalancingRulePropertiesFormat.Probe != nil {
   221  				d.Set("probe_id", config.LoadBalancingRulePropertiesFormat.Probe.ID)
   222  			}
   223  
   224  			if config.LoadBalancingRulePropertiesFormat.LoadDistribution != "" {
   225  				d.Set("load_distribution", config.LoadBalancingRulePropertiesFormat.LoadDistribution)
   226  			}
   227  		}
   228  	}
   229  
   230  	return nil
   231  }
   232  
   233  func resourceArmLoadBalancerRuleDelete(d *schema.ResourceData, meta interface{}) error {
   234  	client := meta.(*ArmClient)
   235  	lbClient := client.loadBalancerClient
   236  
   237  	loadBalancerID := d.Get("loadbalancer_id").(string)
   238  	armMutexKV.Lock(loadBalancerID)
   239  	defer armMutexKV.Unlock(loadBalancerID)
   240  
   241  	loadBalancer, exists, err := retrieveLoadBalancerById(loadBalancerID, meta)
   242  	if err != nil {
   243  		return errwrap.Wrapf("Error Getting LoadBalancer By ID {{err}}", err)
   244  	}
   245  	if !exists {
   246  		d.SetId("")
   247  		return nil
   248  	}
   249  
   250  	_, index, exists := findLoadBalancerRuleByName(loadBalancer, d.Get("name").(string))
   251  	if !exists {
   252  		return nil
   253  	}
   254  
   255  	oldLbRules := *loadBalancer.LoadBalancerPropertiesFormat.LoadBalancingRules
   256  	newLbRules := append(oldLbRules[:index], oldLbRules[index+1:]...)
   257  	loadBalancer.LoadBalancerPropertiesFormat.LoadBalancingRules = &newLbRules
   258  
   259  	resGroup, loadBalancerName, err := resourceGroupAndLBNameFromId(d.Get("loadbalancer_id").(string))
   260  	if err != nil {
   261  		return errwrap.Wrapf("Error Getting LoadBalancer Name and Group: {{err}}", err)
   262  	}
   263  
   264  	_, err = lbClient.CreateOrUpdate(resGroup, loadBalancerName, *loadBalancer, make(chan struct{}))
   265  	if err != nil {
   266  		return errwrap.Wrapf("Error Creating/Updating LoadBalancer {{err}}", err)
   267  	}
   268  
   269  	read, err := lbClient.Get(resGroup, loadBalancerName, "")
   270  	if err != nil {
   271  		return errwrap.Wrapf("Error Getting LoadBalancer {{err}}", err)
   272  	}
   273  	if read.ID == nil {
   274  		return fmt.Errorf("Cannot read LoadBalancer %s (resource group %s) ID", loadBalancerName, resGroup)
   275  	}
   276  
   277  	return nil
   278  }
   279  
   280  func expandAzureRmLoadBalancerRule(d *schema.ResourceData, lb *network.LoadBalancer) (*network.LoadBalancingRule, error) {
   281  
   282  	properties := network.LoadBalancingRulePropertiesFormat{
   283  		Protocol:         network.TransportProtocol(d.Get("protocol").(string)),
   284  		FrontendPort:     azure.Int32(int32(d.Get("frontend_port").(int))),
   285  		BackendPort:      azure.Int32(int32(d.Get("backend_port").(int))),
   286  		EnableFloatingIP: azure.Bool(d.Get("enable_floating_ip").(bool)),
   287  	}
   288  
   289  	if v, ok := d.GetOk("idle_timeout_in_minutes"); ok {
   290  		properties.IdleTimeoutInMinutes = azure.Int32(int32(v.(int)))
   291  	}
   292  
   293  	if v := d.Get("load_distribution").(string); v != "" {
   294  		properties.LoadDistribution = network.LoadDistribution(v)
   295  	}
   296  
   297  	if v := d.Get("frontend_ip_configuration_name").(string); v != "" {
   298  		rule, _, exists := findLoadBalancerFrontEndIpConfigurationByName(lb, v)
   299  		if !exists {
   300  			return nil, fmt.Errorf("[ERROR] Cannot find FrontEnd IP Configuration with the name %s", v)
   301  		}
   302  
   303  		feip := network.SubResource{
   304  			ID: rule.ID,
   305  		}
   306  
   307  		properties.FrontendIPConfiguration = &feip
   308  	}
   309  
   310  	if v := d.Get("backend_address_pool_id").(string); v != "" {
   311  		beAP := network.SubResource{
   312  			ID: &v,
   313  		}
   314  
   315  		properties.BackendAddressPool = &beAP
   316  	}
   317  
   318  	if v := d.Get("probe_id").(string); v != "" {
   319  		pid := network.SubResource{
   320  			ID: &v,
   321  		}
   322  
   323  		properties.Probe = &pid
   324  	}
   325  
   326  	lbRule := network.LoadBalancingRule{
   327  		Name: azure.String(d.Get("name").(string)),
   328  		LoadBalancingRulePropertiesFormat: &properties,
   329  	}
   330  
   331  	return &lbRule, nil
   332  }
   333  
   334  func validateArmLoadBalancerRuleName(v interface{}, k string) (ws []string, errors []error) {
   335  	value := v.(string)
   336  	if !regexp.MustCompile(`^[a-zA-Z_0-9.-]+$`).MatchString(value) {
   337  		errors = append(errors, fmt.Errorf(
   338  			"only word characters, numbers, underscores, periods, and hyphens allowed in %q: %q",
   339  			k, value))
   340  	}
   341  
   342  	if len(value) > 80 {
   343  		errors = append(errors, fmt.Errorf(
   344  			"%q cannot be longer than 80 characters: %q", k, value))
   345  	}
   346  
   347  	if len(value) == 0 {
   348  		errors = append(errors, fmt.Errorf(
   349  			"%q cannot be an empty string: %q", k, value))
   350  	}
   351  	if !regexp.MustCompile(`[a-zA-Z0-9_]$`).MatchString(value) {
   352  		errors = append(errors, fmt.Errorf(
   353  			"%q must end with a word character, number, or underscore: %q", k, value))
   354  	}
   355  
   356  	if !regexp.MustCompile(`^[a-zA-Z0-9]`).MatchString(value) {
   357  		errors = append(errors, fmt.Errorf(
   358  			"%q must start with a word character or number: %q", k, value))
   359  	}
   360  
   361  	return
   362  }