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