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