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