github.com/mapuri/terraform@v0.7.6-0.20161012203214-7e0408293f97/builtin/providers/azurerm/resource_arm_loadbalancer_rule.go (about) 1 package azurerm 2 3 import ( 4 "fmt" 5 "log" 6 "regexp" 7 "time" 8 9 "github.com/Azure/azure-sdk-for-go/arm/network" 10 "github.com/hashicorp/errwrap" 11 "github.com/hashicorp/terraform/helper/resource" 12 "github.com/hashicorp/terraform/helper/schema" 13 "github.com/jen20/riviera/azure" 14 ) 15 16 func resourceArmLoadBalancerRule() *schema.Resource { 17 return &schema.Resource{ 18 Create: resourceArmLoadBalancerRuleCreate, 19 Read: resourceArmLoadBalancerRuleRead, 20 Update: resourceArmLoadBalancerRuleCreate, 21 Delete: resourceArmLoadBalancerRuleDelete, 22 23 Schema: map[string]*schema.Schema{ 24 "name": { 25 Type: schema.TypeString, 26 Required: true, 27 ForceNew: true, 28 ValidateFunc: validateArmLoadBalancerRuleName, 29 }, 30 31 "location": { 32 Type: schema.TypeString, 33 Required: true, 34 ForceNew: true, 35 StateFunc: azureRMNormalizeLocation, 36 }, 37 38 "resource_group_name": { 39 Type: schema.TypeString, 40 Required: true, 41 ForceNew: true, 42 }, 43 44 "loadbalancer_id": { 45 Type: schema.TypeString, 46 Required: true, 47 ForceNew: true, 48 }, 49 50 "frontend_ip_configuration_name": { 51 Type: schema.TypeString, 52 Required: true, 53 }, 54 55 "frontend_ip_configuration_id": { 56 Type: schema.TypeString, 57 Computed: true, 58 }, 59 60 "backend_address_pool_id": { 61 Type: schema.TypeString, 62 Optional: true, 63 Computed: true, 64 }, 65 66 "protocol": { 67 Type: schema.TypeString, 68 Required: true, 69 }, 70 71 "frontend_port": { 72 Type: schema.TypeInt, 73 Required: true, 74 }, 75 76 "backend_port": { 77 Type: schema.TypeInt, 78 Required: true, 79 }, 80 81 "probe_id": { 82 Type: schema.TypeString, 83 Optional: true, 84 Computed: true, 85 }, 86 87 "enable_floating_ip": { 88 Type: schema.TypeBool, 89 Optional: true, 90 Default: false, 91 }, 92 93 "idle_timeout_in_minutes": { 94 Type: schema.TypeInt, 95 Optional: true, 96 Computed: true, 97 }, 98 99 "load_distribution": { 100 Type: schema.TypeString, 101 Optional: true, 102 Computed: true, 103 }, 104 }, 105 } 106 } 107 108 func resourceArmLoadBalancerRuleCreate(d *schema.ResourceData, meta interface{}) error { 109 client := meta.(*ArmClient) 110 lbClient := client.loadBalancerClient 111 112 loadBalancer, exists, err := retrieveLoadBalancerById(d.Get("loadbalancer_id").(string), meta) 113 if err != nil { 114 return errwrap.Wrapf("Error Getting LoadBalancer By ID {{err}}", err) 115 } 116 if !exists { 117 d.SetId("") 118 log.Printf("[INFO] LoadBalancer %q not found. Removing from state", d.Get("name").(string)) 119 return nil 120 } 121 122 _, _, exists = findLoadBalancerRuleByName(loadBalancer, d.Get("name").(string)) 123 if exists { 124 return fmt.Errorf("A LoadBalancer Rule with name %q already exists.", d.Get("name").(string)) 125 } 126 127 newLbRule, err := expandAzureRmLoadBalancerRule(d, loadBalancer) 128 if err != nil { 129 return errwrap.Wrapf("Error Exanding LoadBalancer Rule {{err}}", err) 130 } 131 132 lbRules := append(*loadBalancer.Properties.LoadBalancingRules, *newLbRule) 133 loadBalancer.Properties.LoadBalancingRules = &lbRules 134 resGroup, loadBalancerName, err := resourceGroupAndLBNameFromId(d.Get("loadbalancer_id").(string)) 135 if err != nil { 136 return errwrap.Wrapf("Error Getting LoadBalancer Name and Group: {{err}}", err) 137 } 138 139 _, err = lbClient.CreateOrUpdate(resGroup, loadBalancerName, *loadBalancer, make(chan struct{})) 140 if err != nil { 141 return errwrap.Wrapf("Error Creating/Updating LoadBalancer {{err}}", err) 142 } 143 144 read, err := lbClient.Get(resGroup, loadBalancerName, "") 145 if err != nil { 146 return errwrap.Wrapf("Error Getting LoadBalancer {{err}}", err) 147 } 148 if read.ID == nil { 149 return fmt.Errorf("Cannot read LoadBalancer %s (resource group %s) ID", loadBalancerName, resGroup) 150 } 151 152 d.SetId(*read.ID) 153 154 log.Printf("[DEBUG] Waiting for LoadBalancer (%s) to become available", loadBalancerName) 155 stateConf := &resource.StateChangeConf{ 156 Pending: []string{"Accepted", "Updating"}, 157 Target: []string{"Succeeded"}, 158 Refresh: loadbalancerStateRefreshFunc(client, resGroup, loadBalancerName), 159 Timeout: 10 * time.Minute, 160 } 161 if _, err := stateConf.WaitForState(); err != nil { 162 return fmt.Errorf("Error waiting for LoadBalancer (%s) to become available: %s", loadBalancerName, err) 163 } 164 165 return resourceArmLoadBalancerRuleRead(d, meta) 166 } 167 168 func resourceArmLoadBalancerRuleRead(d *schema.ResourceData, meta interface{}) error { 169 loadBalancer, exists, err := retrieveLoadBalancerById(d.Id(), meta) 170 if err != nil { 171 return errwrap.Wrapf("Error Getting LoadBalancer By ID {{err}}", err) 172 } 173 if !exists { 174 d.SetId("") 175 log.Printf("[INFO] LoadBalancer %q not found. Removing from state", d.Get("name").(string)) 176 return nil 177 } 178 179 configs := *loadBalancer.Properties.LoadBalancingRules 180 for _, config := range configs { 181 if *config.Name == d.Get("name").(string) { 182 d.Set("name", config.Name) 183 184 d.Set("protocol", config.Properties.Protocol) 185 d.Set("frontend_port", config.Properties.FrontendPort) 186 d.Set("backend_port", config.Properties.BackendPort) 187 188 if config.Properties.EnableFloatingIP != nil { 189 d.Set("enable_floating_ip", config.Properties.EnableFloatingIP) 190 } 191 192 if config.Properties.IdleTimeoutInMinutes != nil { 193 d.Set("idle_timeout_in_minutes", config.Properties.IdleTimeoutInMinutes) 194 } 195 196 if config.Properties.FrontendIPConfiguration != nil { 197 d.Set("frontend_ip_configuration_id", config.Properties.FrontendIPConfiguration.ID) 198 } 199 200 if config.Properties.BackendAddressPool != nil { 201 d.Set("backend_address_pool_id", config.Properties.BackendAddressPool.ID) 202 } 203 204 if config.Properties.Probe != nil { 205 d.Set("probe_id", config.Properties.Probe.ID) 206 } 207 208 if config.Properties.LoadDistribution != "" { 209 d.Set("load_distribution", config.Properties.LoadDistribution) 210 } 211 } 212 } 213 214 return nil 215 } 216 217 func resourceArmLoadBalancerRuleDelete(d *schema.ResourceData, meta interface{}) error { 218 client := meta.(*ArmClient) 219 lbClient := client.loadBalancerClient 220 221 loadBalancer, exists, err := retrieveLoadBalancerById(d.Get("loadbalancer_id").(string), meta) 222 if err != nil { 223 return errwrap.Wrapf("Error Getting LoadBalancer By ID {{err}}", err) 224 } 225 if !exists { 226 d.SetId("") 227 return nil 228 } 229 230 _, index, exists := findLoadBalancerRuleByName(loadBalancer, d.Get("name").(string)) 231 if !exists { 232 return nil 233 } 234 235 oldLbRules := *loadBalancer.Properties.LoadBalancingRules 236 newLbRules := append(oldLbRules[:index], oldLbRules[index+1:]...) 237 loadBalancer.Properties.LoadBalancingRules = &newLbRules 238 239 resGroup, loadBalancerName, err := resourceGroupAndLBNameFromId(d.Get("loadbalancer_id").(string)) 240 if err != nil { 241 return errwrap.Wrapf("Error Getting LoadBalancer Name and Group: {{err}}", err) 242 } 243 244 _, err = lbClient.CreateOrUpdate(resGroup, loadBalancerName, *loadBalancer, make(chan struct{})) 245 if err != nil { 246 return errwrap.Wrapf("Error Creating/Updating LoadBalancer {{err}}", err) 247 } 248 249 read, err := lbClient.Get(resGroup, loadBalancerName, "") 250 if err != nil { 251 return errwrap.Wrapf("Error Getting LoadBalancer {{err}}", err) 252 } 253 if read.ID == nil { 254 return fmt.Errorf("Cannot read LoadBalancer %s (resource group %s) ID", loadBalancerName, resGroup) 255 } 256 257 return nil 258 } 259 260 func expandAzureRmLoadBalancerRule(d *schema.ResourceData, lb *network.LoadBalancer) (*network.LoadBalancingRule, error) { 261 262 properties := network.LoadBalancingRulePropertiesFormat{ 263 Protocol: network.TransportProtocol(d.Get("protocol").(string)), 264 FrontendPort: azure.Int32(int32(d.Get("frontend_port").(int))), 265 BackendPort: azure.Int32(int32(d.Get("backend_port").(int))), 266 EnableFloatingIP: azure.Bool(d.Get("enable_floating_ip").(bool)), 267 } 268 269 if v, ok := d.GetOk("idle_timeout_in_minutes"); ok { 270 properties.IdleTimeoutInMinutes = azure.Int32(int32(v.(int))) 271 } 272 273 if v := d.Get("load_distribution").(string); v != "" { 274 properties.LoadDistribution = network.LoadDistribution(v) 275 } 276 277 if v := d.Get("frontend_ip_configuration_name").(string); v != "" { 278 rule, _, exists := findLoadBalancerFrontEndIpConfigurationByName(lb, v) 279 if !exists { 280 return nil, fmt.Errorf("[ERROR] Cannot find FrontEnd IP Configuration with the name %s", v) 281 } 282 283 feip := network.SubResource{ 284 ID: rule.ID, 285 } 286 287 properties.FrontendIPConfiguration = &feip 288 } 289 290 if v := d.Get("backend_address_pool_id").(string); v != "" { 291 beAP := network.SubResource{ 292 ID: &v, 293 } 294 295 properties.BackendAddressPool = &beAP 296 } 297 298 if v := d.Get("probe_id").(string); v != "" { 299 pid := network.SubResource{ 300 ID: &v, 301 } 302 303 properties.Probe = &pid 304 } 305 306 lbRule := network.LoadBalancingRule{ 307 Name: azure.String(d.Get("name").(string)), 308 Properties: &properties, 309 } 310 311 return &lbRule, nil 312 } 313 314 func validateArmLoadBalancerRuleName(v interface{}, k string) (ws []string, errors []error) { 315 value := v.(string) 316 if !regexp.MustCompile(`^[a-zA-Z._-]+$`).MatchString(value) { 317 errors = append(errors, fmt.Errorf( 318 "only word characters and hyphens allowed in %q: %q", 319 k, value)) 320 } 321 322 if len(value) > 80 { 323 errors = append(errors, fmt.Errorf( 324 "%q cannot be longer than 80 characters: %q", k, value)) 325 } 326 327 if len(value) == 0 { 328 errors = append(errors, fmt.Errorf( 329 "%q cannot be an empty string: %q", k, value)) 330 } 331 if !regexp.MustCompile(`[a-zA-Z]$`).MatchString(value) { 332 errors = append(errors, fmt.Errorf( 333 "%q must end with a word character: %q", k, value)) 334 } 335 336 if !regexp.MustCompile(`^[a-zA-Z]`).MatchString(value) { 337 errors = append(errors, fmt.Errorf( 338 "%q must start with a word character: %q", k, value)) 339 } 340 341 return 342 }