github.com/minamijoyo/terraform@v0.7.8-0.20161029001309-18b3736ba44b/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": {
    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": {
    54  				Type:     schema.TypeInt,
    55  				Required: true,
    56  			},
    57  
    58  			"backend_port": {
    59  				Type:     schema.TypeInt,
    60  				Required: true,
    61  			},
    62  
    63  			"frontend_ip_configuration_name": {
    64  				Type:     schema.TypeString,
    65  				Required: true,
    66  			},
    67  
    68  			"frontend_ip_configuration_id": {
    69  				Type:     schema.TypeString,
    70  				Computed: true,
    71  			},
    72  
    73  			"backend_ip_configuration_id": {
    74  				Type:     schema.TypeString,
    75  				Computed: true,
    76  			},
    77  		},
    78  	}
    79  }
    80  
    81  func resourceArmLoadBalancerNatRuleCreate(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 = findLoadBalancerNatRuleByName(loadBalancer, d.Get("name").(string))
   100  	if exists {
   101  		return fmt.Errorf("A NAT Rule with name %q already exists.", d.Get("name").(string))
   102  	}
   103  
   104  	newNatRule, err := expandAzureRmLoadBalancerNatRule(d, loadBalancer)
   105  	if err != nil {
   106  		return errwrap.Wrapf("Error Expanding NAT Rule {{err}}", err)
   107  	}
   108  
   109  	natRules := append(*loadBalancer.Properties.InboundNatRules, *newNatRule)
   110  	loadBalancer.Properties.InboundNatRules = &natRules
   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 natRule_id string
   130  	for _, InboundNatRule := range *(*read.Properties).InboundNatRules {
   131  		if *InboundNatRule.Name == d.Get("name").(string) {
   132  			natRule_id = *InboundNatRule.ID
   133  		}
   134  	}
   135  
   136  	if natRule_id != "" {
   137  		d.SetId(natRule_id)
   138  	} else {
   139  		return fmt.Errorf("Cannot find created LoadBalancer NAT Rule ID %q", natRule_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 resourceArmLoadBalancerNatRuleRead(d, meta)
   154  }
   155  
   156  func resourceArmLoadBalancerNatRuleRead(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.InboundNatRules
   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", config.Properties.FrontendPort)
   174  			d.Set("backend_port", config.Properties.BackendPort)
   175  
   176  			if config.Properties.FrontendIPConfiguration != nil {
   177  				d.Set("frontend_ip_configuration_id", config.Properties.FrontendIPConfiguration.ID)
   178  			}
   179  
   180  			if config.Properties.BackendIPConfiguration != nil {
   181  				d.Set("backend_ip_configuration_id", config.Properties.BackendIPConfiguration.ID)
   182  			}
   183  
   184  			break
   185  		}
   186  	}
   187  
   188  	return nil
   189  }
   190  
   191  func resourceArmLoadBalancerNatRuleDelete(d *schema.ResourceData, meta interface{}) error {
   192  	client := meta.(*ArmClient)
   193  	lbClient := client.loadBalancerClient
   194  
   195  	loadBalancerID := d.Get("loadbalancer_id").(string)
   196  	armMutexKV.Lock(loadBalancerID)
   197  	defer armMutexKV.Unlock(loadBalancerID)
   198  
   199  	loadBalancer, exists, err := retrieveLoadBalancerById(loadBalancerID, meta)
   200  	if err != nil {
   201  		return errwrap.Wrapf("Error Getting LoadBalancer By ID {{err}}", err)
   202  	}
   203  	if !exists {
   204  		d.SetId("")
   205  		return nil
   206  	}
   207  
   208  	_, index, exists := findLoadBalancerNatRuleByName(loadBalancer, d.Get("name").(string))
   209  	if !exists {
   210  		return nil
   211  	}
   212  
   213  	oldNatRules := *loadBalancer.Properties.InboundNatRules
   214  	newNatRules := append(oldNatRules[:index], oldNatRules[index+1:]...)
   215  	loadBalancer.Properties.InboundNatRules = &newNatRules
   216  
   217  	resGroup, loadBalancerName, err := resourceGroupAndLBNameFromId(d.Get("loadbalancer_id").(string))
   218  	if err != nil {
   219  		return errwrap.Wrapf("Error Getting LoadBalancer Name and Group: {{err}}", err)
   220  	}
   221  
   222  	_, err = lbClient.CreateOrUpdate(resGroup, loadBalancerName, *loadBalancer, make(chan struct{}))
   223  	if err != nil {
   224  		return errwrap.Wrapf("Error Creating/Updating LoadBalancer {{err}}", err)
   225  	}
   226  
   227  	read, err := lbClient.Get(resGroup, loadBalancerName, "")
   228  	if err != nil {
   229  		return errwrap.Wrapf("Error Getting LoadBalancer {{err}}", err)
   230  	}
   231  	if read.ID == nil {
   232  		return fmt.Errorf("Cannot read LoadBalancer %s (resource group %s) ID", loadBalancerName, resGroup)
   233  	}
   234  
   235  	return nil
   236  }
   237  
   238  func expandAzureRmLoadBalancerNatRule(d *schema.ResourceData, lb *network.LoadBalancer) (*network.InboundNatRule, error) {
   239  
   240  	properties := network.InboundNatRulePropertiesFormat{
   241  		Protocol:     network.TransportProtocol(d.Get("protocol").(string)),
   242  		FrontendPort: azure.Int32(int32(d.Get("frontend_port").(int))),
   243  		BackendPort:  azure.Int32(int32(d.Get("backend_port").(int))),
   244  	}
   245  
   246  	if v := d.Get("frontend_ip_configuration_name").(string); v != "" {
   247  		rule, _, exists := findLoadBalancerFrontEndIpConfigurationByName(lb, v)
   248  		if !exists {
   249  			return nil, fmt.Errorf("[ERROR] Cannot find FrontEnd IP Configuration with the name %s", v)
   250  		}
   251  
   252  		feip := network.SubResource{
   253  			ID: rule.ID,
   254  		}
   255  
   256  		properties.FrontendIPConfiguration = &feip
   257  	}
   258  
   259  	natRule := network.InboundNatRule{
   260  		Name:       azure.String(d.Get("name").(string)),
   261  		Properties: &properties,
   262  	}
   263  
   264  	return &natRule, nil
   265  }