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