github.com/aspring/terraform@v0.8.2-0.20161216122603-6a8619a5db2e/builtin/providers/azurerm/resource_arm_loadbalancer_nat_rule.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 resourceArmLoadBalancerNatRule() *schema.Resource {
    16  	return &schema.Resource{
    17  		Create: resourceArmLoadBalancerNatRuleCreate,
    18  		Read:   resourceArmLoadBalancerNatRuleRead,
    19  		Update: resourceArmLoadBalancerNatRuleCreate,
    20  		Delete: resourceArmLoadBalancerNatRuleDelete,
    21  
    22  		Schema: map[string]*schema.Schema{
    23  			"name": {
    24  				Type:     schema.TypeString,
    25  				Required: true,
    26  				ForceNew: true,
    27  			},
    28  
    29  			"location": locationSchema(),
    30  
    31  			"resource_group_name": {
    32  				Type:     schema.TypeString,
    33  				Required: true,
    34  				ForceNew: true,
    35  			},
    36  
    37  			"loadbalancer_id": {
    38  				Type:     schema.TypeString,
    39  				Required: true,
    40  				ForceNew: true,
    41  			},
    42  
    43  			"protocol": {
    44  				Type:     schema.TypeString,
    45  				Required: true,
    46  			},
    47  
    48  			"frontend_port": {
    49  				Type:     schema.TypeInt,
    50  				Required: true,
    51  			},
    52  
    53  			"backend_port": {
    54  				Type:     schema.TypeInt,
    55  				Required: true,
    56  			},
    57  
    58  			"frontend_ip_configuration_name": {
    59  				Type:     schema.TypeString,
    60  				Required: true,
    61  			},
    62  
    63  			"frontend_ip_configuration_id": {
    64  				Type:     schema.TypeString,
    65  				Computed: true,
    66  			},
    67  
    68  			"backend_ip_configuration_id": {
    69  				Type:     schema.TypeString,
    70  				Computed: true,
    71  			},
    72  		},
    73  	}
    74  }
    75  
    76  func resourceArmLoadBalancerNatRuleCreate(d *schema.ResourceData, meta interface{}) error {
    77  	client := meta.(*ArmClient)
    78  	lbClient := client.loadBalancerClient
    79  
    80  	loadBalancerID := d.Get("loadbalancer_id").(string)
    81  	armMutexKV.Lock(loadBalancerID)
    82  	defer armMutexKV.Unlock(loadBalancerID)
    83  
    84  	loadBalancer, exists, err := retrieveLoadBalancerById(loadBalancerID, meta)
    85  	if err != nil {
    86  		return errwrap.Wrapf("Error Getting LoadBalancer By ID {{err}}", err)
    87  	}
    88  	if !exists {
    89  		d.SetId("")
    90  		log.Printf("[INFO] LoadBalancer %q not found. Removing from state", d.Get("name").(string))
    91  		return nil
    92  	}
    93  
    94  	newNatRule, err := expandAzureRmLoadBalancerNatRule(d, loadBalancer)
    95  	if err != nil {
    96  		return errwrap.Wrapf("Error Expanding NAT Rule {{err}}", err)
    97  	}
    98  
    99  	natRules := append(*loadBalancer.LoadBalancerPropertiesFormat.InboundNatRules, *newNatRule)
   100  
   101  	existingNatRule, existingNatRuleIndex, exists := findLoadBalancerNatRuleByName(loadBalancer, d.Get("name").(string))
   102  	if exists {
   103  		if d.Id() == *existingNatRule.ID {
   104  			// this probe is being updated remove old copy from the slice
   105  			natRules = append(natRules[:existingNatRuleIndex], natRules[existingNatRuleIndex+1:]...)
   106  		} else {
   107  			return fmt.Errorf("A NAT Rule with name %q already exists.", d.Get("name").(string))
   108  		}
   109  	}
   110  
   111  	loadBalancer.LoadBalancerPropertiesFormat.InboundNatRules = &natRules
   112  	resGroup, loadBalancerName, err := resourceGroupAndLBNameFromId(d.Get("loadbalancer_id").(string))
   113  	if err != nil {
   114  		return errwrap.Wrapf("Error Getting LoadBalancer Name and Group: {{err}}", err)
   115  	}
   116  
   117  	_, err = lbClient.CreateOrUpdate(resGroup, loadBalancerName, *loadBalancer, make(chan struct{}))
   118  	if err != nil {
   119  		return errwrap.Wrapf("Error Creating / Updating LoadBalancer {{err}}", err)
   120  	}
   121  
   122  	read, err := lbClient.Get(resGroup, loadBalancerName, "")
   123  	if err != nil {
   124  		return errwrap.Wrapf("Error Getting LoadBalancer {{err}}", err)
   125  	}
   126  	if read.ID == nil {
   127  		return fmt.Errorf("Cannot read LoadBalancer %s (resource group %s) ID", loadBalancerName, resGroup)
   128  	}
   129  
   130  	var natRule_id string
   131  	for _, InboundNatRule := range *(*read.LoadBalancerPropertiesFormat).InboundNatRules {
   132  		if *InboundNatRule.Name == d.Get("name").(string) {
   133  			natRule_id = *InboundNatRule.ID
   134  		}
   135  	}
   136  
   137  	if natRule_id != "" {
   138  		d.SetId(natRule_id)
   139  	} else {
   140  		return fmt.Errorf("Cannot find created LoadBalancer NAT Rule ID %q", natRule_id)
   141  	}
   142  
   143  	log.Printf("[DEBUG] Waiting for LoadBalancer (%s) to become available", loadBalancerName)
   144  	stateConf := &resource.StateChangeConf{
   145  		Pending: []string{"Accepted", "Updating"},
   146  		Target:  []string{"Succeeded"},
   147  		Refresh: loadbalancerStateRefreshFunc(client, resGroup, loadBalancerName),
   148  		Timeout: 10 * time.Minute,
   149  	}
   150  	if _, err := stateConf.WaitForState(); err != nil {
   151  		return fmt.Errorf("Error waiting for LoadBalancer (%s) to become available: %s", loadBalancerName, err)
   152  	}
   153  
   154  	return resourceArmLoadBalancerNatRuleRead(d, meta)
   155  }
   156  
   157  func resourceArmLoadBalancerNatRuleRead(d *schema.ResourceData, meta interface{}) error {
   158  	loadBalancer, exists, err := retrieveLoadBalancerById(d.Get("loadbalancer_id").(string), meta)
   159  	if err != nil {
   160  		return errwrap.Wrapf("Error Getting LoadBalancer By ID {{err}}", err)
   161  	}
   162  	if !exists {
   163  		d.SetId("")
   164  		log.Printf("[INFO] LoadBalancer %q not found. Removing from state", d.Get("name").(string))
   165  		return nil
   166  	}
   167  
   168  	configs := *loadBalancer.LoadBalancerPropertiesFormat.InboundNatRules
   169  	for _, config := range configs {
   170  		if *config.Name == d.Get("name").(string) {
   171  			d.Set("name", config.Name)
   172  
   173  			d.Set("protocol", config.InboundNatRulePropertiesFormat.Protocol)
   174  			d.Set("frontend_port", config.InboundNatRulePropertiesFormat.FrontendPort)
   175  			d.Set("backend_port", config.InboundNatRulePropertiesFormat.BackendPort)
   176  
   177  			if config.InboundNatRulePropertiesFormat.FrontendIPConfiguration != nil {
   178  				d.Set("frontend_ip_configuration_id", config.InboundNatRulePropertiesFormat.FrontendIPConfiguration.ID)
   179  			}
   180  
   181  			if config.InboundNatRulePropertiesFormat.BackendIPConfiguration != nil {
   182  				d.Set("backend_ip_configuration_id", config.InboundNatRulePropertiesFormat.BackendIPConfiguration.ID)
   183  			}
   184  
   185  			break
   186  		}
   187  	}
   188  
   189  	return nil
   190  }
   191  
   192  func resourceArmLoadBalancerNatRuleDelete(d *schema.ResourceData, meta interface{}) error {
   193  	client := meta.(*ArmClient)
   194  	lbClient := client.loadBalancerClient
   195  
   196  	loadBalancerID := d.Get("loadbalancer_id").(string)
   197  	armMutexKV.Lock(loadBalancerID)
   198  	defer armMutexKV.Unlock(loadBalancerID)
   199  
   200  	loadBalancer, exists, err := retrieveLoadBalancerById(loadBalancerID, meta)
   201  	if err != nil {
   202  		return errwrap.Wrapf("Error Getting LoadBalancer By ID {{err}}", err)
   203  	}
   204  	if !exists {
   205  		d.SetId("")
   206  		return nil
   207  	}
   208  
   209  	_, index, exists := findLoadBalancerNatRuleByName(loadBalancer, d.Get("name").(string))
   210  	if !exists {
   211  		return nil
   212  	}
   213  
   214  	oldNatRules := *loadBalancer.LoadBalancerPropertiesFormat.InboundNatRules
   215  	newNatRules := append(oldNatRules[:index], oldNatRules[index+1:]...)
   216  	loadBalancer.LoadBalancerPropertiesFormat.InboundNatRules = &newNatRules
   217  
   218  	resGroup, loadBalancerName, err := resourceGroupAndLBNameFromId(d.Get("loadbalancer_id").(string))
   219  	if err != nil {
   220  		return errwrap.Wrapf("Error Getting LoadBalancer Name and Group: {{err}}", err)
   221  	}
   222  
   223  	_, err = lbClient.CreateOrUpdate(resGroup, loadBalancerName, *loadBalancer, make(chan struct{}))
   224  	if err != nil {
   225  		return errwrap.Wrapf("Error Creating/Updating LoadBalancer {{err}}", err)
   226  	}
   227  
   228  	read, err := lbClient.Get(resGroup, loadBalancerName, "")
   229  	if err != nil {
   230  		return errwrap.Wrapf("Error Getting LoadBalancer {{err}}", err)
   231  	}
   232  	if read.ID == nil {
   233  		return fmt.Errorf("Cannot read LoadBalancer %s (resource group %s) ID", loadBalancerName, resGroup)
   234  	}
   235  
   236  	return nil
   237  }
   238  
   239  func expandAzureRmLoadBalancerNatRule(d *schema.ResourceData, lb *network.LoadBalancer) (*network.InboundNatRule, error) {
   240  
   241  	properties := network.InboundNatRulePropertiesFormat{
   242  		Protocol:     network.TransportProtocol(d.Get("protocol").(string)),
   243  		FrontendPort: azure.Int32(int32(d.Get("frontend_port").(int))),
   244  		BackendPort:  azure.Int32(int32(d.Get("backend_port").(int))),
   245  	}
   246  
   247  	if v := d.Get("frontend_ip_configuration_name").(string); v != "" {
   248  		rule, _, exists := findLoadBalancerFrontEndIpConfigurationByName(lb, v)
   249  		if !exists {
   250  			return nil, fmt.Errorf("[ERROR] Cannot find FrontEnd IP Configuration with the name %s", v)
   251  		}
   252  
   253  		feip := network.SubResource{
   254  			ID: rule.ID,
   255  		}
   256  
   257  		properties.FrontendIPConfiguration = &feip
   258  	}
   259  
   260  	natRule := network.InboundNatRule{
   261  		Name: azure.String(d.Get("name").(string)),
   262  		InboundNatRulePropertiesFormat: &properties,
   263  	}
   264  
   265  	return &natRule, nil
   266  }