github.com/ves/terraform@v0.8.0-beta2/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  
    22  		Schema: map[string]*schema.Schema{
    23  			"name": {
    24  				Type:     schema.TypeString,
    25  				Required: true,
    26  				ForceNew: true,
    27  			},
    28  
    29  			"location": {
    30  				Type:      schema.TypeString,
    31  				Required:  true,
    32  				ForceNew:  true,
    33  				StateFunc: azureRMNormalizeLocation,
    34  			},
    35  
    36  			"resource_group_name": {
    37  				Type:     schema.TypeString,
    38  				Required: true,
    39  				ForceNew: true,
    40  			},
    41  
    42  			"loadbalancer_id": {
    43  				Type:     schema.TypeString,
    44  				Required: true,
    45  				ForceNew: true,
    46  			},
    47  
    48  			"protocol": {
    49  				Type:     schema.TypeString,
    50  				Required: true,
    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.Properties.InboundNatPools, *newNatPool)
   105  
   106  	existingNatPool, existingNatPoolIndex, exists := findLoadBalancerNatPoolByName(loadBalancer, d.Get("name").(string))
   107  	if exists {
   108  		if d.Id() == *existingNatPool.ID {
   109  			// this probe is being updated remove old copy from the slice
   110  			natPools = append(natPools[:existingNatPoolIndex], natPools[existingNatPoolIndex+1:]...)
   111  		} else {
   112  			return fmt.Errorf("A NAT Pool with name %q already exists.", d.Get("name").(string))
   113  		}
   114  	}
   115  
   116  	loadBalancer.Properties.InboundNatPools = &natPools
   117  	resGroup, loadBalancerName, err := resourceGroupAndLBNameFromId(d.Get("loadbalancer_id").(string))
   118  	if err != nil {
   119  		return errwrap.Wrapf("Error Getting LoadBalancer Name and Group: {{err}}", err)
   120  	}
   121  
   122  	_, err = lbClient.CreateOrUpdate(resGroup, loadBalancerName, *loadBalancer, make(chan struct{}))
   123  	if err != nil {
   124  		return errwrap.Wrapf("Error Creating/Updating LoadBalancer {{err}}", err)
   125  	}
   126  
   127  	read, err := lbClient.Get(resGroup, loadBalancerName, "")
   128  	if err != nil {
   129  		return errwrap.Wrapf("Error Getting LoadBalancer {{err}}", err)
   130  	}
   131  	if read.ID == nil {
   132  		return fmt.Errorf("Cannot read LoadBalancer %s (resource group %s) ID", loadBalancerName, resGroup)
   133  	}
   134  
   135  	var natPool_id string
   136  	for _, InboundNatPool := range *(*read.Properties).InboundNatPools {
   137  		if *InboundNatPool.Name == d.Get("name").(string) {
   138  			natPool_id = *InboundNatPool.ID
   139  		}
   140  	}
   141  
   142  	if natPool_id != "" {
   143  		d.SetId(natPool_id)
   144  	} else {
   145  		return fmt.Errorf("Cannot find created LoadBalancer NAT Pool ID %q", natPool_id)
   146  	}
   147  
   148  	log.Printf("[DEBUG] Waiting for LoadBalancer (%s) to become available", loadBalancerName)
   149  	stateConf := &resource.StateChangeConf{
   150  		Pending: []string{"Accepted", "Updating"},
   151  		Target:  []string{"Succeeded"},
   152  		Refresh: loadbalancerStateRefreshFunc(client, resGroup, loadBalancerName),
   153  		Timeout: 10 * time.Minute,
   154  	}
   155  	if _, err := stateConf.WaitForState(); err != nil {
   156  		return fmt.Errorf("Error waiting for LoadBalancer (%s) to become available: %s", loadBalancerName, err)
   157  	}
   158  
   159  	return resourceArmLoadBalancerNatPoolRead(d, meta)
   160  }
   161  
   162  func resourceArmLoadBalancerNatPoolRead(d *schema.ResourceData, meta interface{}) error {
   163  	loadBalancer, exists, err := retrieveLoadBalancerById(d.Get("loadbalancer_id").(string), meta)
   164  	if err != nil {
   165  		return errwrap.Wrapf("Error Getting LoadBalancer By ID {{err}}", err)
   166  	}
   167  	if !exists {
   168  		d.SetId("")
   169  		log.Printf("[INFO] LoadBalancer %q not found. Removing from state", d.Get("name").(string))
   170  		return nil
   171  	}
   172  
   173  	configs := *loadBalancer.Properties.InboundNatPools
   174  	for _, config := range configs {
   175  		if *config.Name == d.Get("name").(string) {
   176  			d.Set("name", config.Name)
   177  
   178  			d.Set("protocol", config.Properties.Protocol)
   179  			d.Set("frontend_port_start", config.Properties.FrontendPortRangeStart)
   180  			d.Set("frontend_port_end", config.Properties.FrontendPortRangeEnd)
   181  			d.Set("backend_port", config.Properties.BackendPort)
   182  
   183  			if config.Properties.FrontendIPConfiguration != nil {
   184  				d.Set("frontend_ip_configuration_id", config.Properties.FrontendIPConfiguration.ID)
   185  			}
   186  
   187  			break
   188  		}
   189  	}
   190  
   191  	return nil
   192  }
   193  
   194  func resourceArmLoadBalancerNatPoolDelete(d *schema.ResourceData, meta interface{}) error {
   195  	client := meta.(*ArmClient)
   196  	lbClient := client.loadBalancerClient
   197  
   198  	loadBalancerID := d.Get("loadbalancer_id").(string)
   199  	armMutexKV.Lock(loadBalancerID)
   200  	defer armMutexKV.Unlock(loadBalancerID)
   201  
   202  	loadBalancer, exists, err := retrieveLoadBalancerById(loadBalancerID, meta)
   203  	if err != nil {
   204  		return errwrap.Wrapf("Error Getting LoadBalancer By ID {{err}}", err)
   205  	}
   206  	if !exists {
   207  		d.SetId("")
   208  		return nil
   209  	}
   210  
   211  	_, index, exists := findLoadBalancerNatPoolByName(loadBalancer, d.Get("name").(string))
   212  	if !exists {
   213  		return nil
   214  	}
   215  
   216  	oldNatPools := *loadBalancer.Properties.InboundNatPools
   217  	newNatPools := append(oldNatPools[:index], oldNatPools[index+1:]...)
   218  	loadBalancer.Properties.InboundNatPools = &newNatPools
   219  
   220  	resGroup, loadBalancerName, err := resourceGroupAndLBNameFromId(d.Get("loadbalancer_id").(string))
   221  	if err != nil {
   222  		return errwrap.Wrapf("Error Getting LoadBalancer Name and Group: {{err}}", err)
   223  	}
   224  
   225  	_, err = lbClient.CreateOrUpdate(resGroup, loadBalancerName, *loadBalancer, make(chan struct{}))
   226  	if err != nil {
   227  		return errwrap.Wrapf("Error Creating/Updating LoadBalancer {{err}}", err)
   228  	}
   229  
   230  	read, err := lbClient.Get(resGroup, loadBalancerName, "")
   231  	if err != nil {
   232  		return errwrap.Wrapf("Error Getting LoadBalancer {{err}}", err)
   233  	}
   234  	if read.ID == nil {
   235  		return fmt.Errorf("Cannot read LoadBalancer %s (resource group %s) ID", loadBalancerName, resGroup)
   236  	}
   237  
   238  	return nil
   239  }
   240  
   241  func expandAzureRmLoadBalancerNatPool(d *schema.ResourceData, lb *network.LoadBalancer) (*network.InboundNatPool, error) {
   242  
   243  	properties := network.InboundNatPoolPropertiesFormat{
   244  		Protocol:               network.TransportProtocol(d.Get("protocol").(string)),
   245  		FrontendPortRangeStart: azure.Int32(int32(d.Get("frontend_port_start").(int))),
   246  		FrontendPortRangeEnd:   azure.Int32(int32(d.Get("frontend_port_end").(int))),
   247  		BackendPort:            azure.Int32(int32(d.Get("backend_port").(int))),
   248  	}
   249  
   250  	if v := d.Get("frontend_ip_configuration_name").(string); v != "" {
   251  		rule, _, exists := findLoadBalancerFrontEndIpConfigurationByName(lb, v)
   252  		if !exists {
   253  			return nil, fmt.Errorf("[ERROR] Cannot find FrontEnd IP Configuration with the name %s", v)
   254  		}
   255  
   256  		feip := network.SubResource{
   257  			ID: rule.ID,
   258  		}
   259  
   260  		properties.FrontendIPConfiguration = &feip
   261  	}
   262  
   263  	natPool := network.InboundNatPool{
   264  		Name:       azure.String(d.Get("name").(string)),
   265  		Properties: &properties,
   266  	}
   267  
   268  	return &natPool, nil
   269  }