github.com/keshavdv/terraform@v0.7.0-rc2.0.20160711232630-d69256dcb425/builtin/providers/aws/resource_aws_elb.go (about) 1 package aws 2 3 import ( 4 "bytes" 5 "fmt" 6 "log" 7 "strings" 8 "time" 9 10 "github.com/aws/aws-sdk-go/aws" 11 "github.com/aws/aws-sdk-go/aws/awserr" 12 "github.com/aws/aws-sdk-go/service/ec2" 13 "github.com/aws/aws-sdk-go/service/elb" 14 "github.com/hashicorp/terraform/helper/hashcode" 15 "github.com/hashicorp/terraform/helper/resource" 16 "github.com/hashicorp/terraform/helper/schema" 17 ) 18 19 func resourceAwsElb() *schema.Resource { 20 return &schema.Resource{ 21 Create: resourceAwsElbCreate, 22 Read: resourceAwsElbRead, 23 Update: resourceAwsElbUpdate, 24 Delete: resourceAwsElbDelete, 25 Importer: &schema.ResourceImporter{ 26 State: schema.ImportStatePassthrough, 27 }, 28 29 Schema: map[string]*schema.Schema{ 30 "name": &schema.Schema{ 31 Type: schema.TypeString, 32 Optional: true, 33 Computed: true, 34 ForceNew: true, 35 ValidateFunc: validateElbName, 36 }, 37 38 "internal": &schema.Schema{ 39 Type: schema.TypeBool, 40 Optional: true, 41 ForceNew: true, 42 Computed: true, 43 }, 44 45 "cross_zone_load_balancing": &schema.Schema{ 46 Type: schema.TypeBool, 47 Optional: true, 48 Default: true, 49 }, 50 51 "availability_zones": &schema.Schema{ 52 Type: schema.TypeSet, 53 Elem: &schema.Schema{Type: schema.TypeString}, 54 Optional: true, 55 Computed: true, 56 Set: schema.HashString, 57 }, 58 59 "instances": &schema.Schema{ 60 Type: schema.TypeSet, 61 Elem: &schema.Schema{Type: schema.TypeString}, 62 Optional: true, 63 Computed: true, 64 Set: schema.HashString, 65 }, 66 67 "security_groups": &schema.Schema{ 68 Type: schema.TypeSet, 69 Elem: &schema.Schema{Type: schema.TypeString}, 70 Optional: true, 71 Computed: true, 72 Set: schema.HashString, 73 }, 74 75 "source_security_group": &schema.Schema{ 76 Type: schema.TypeString, 77 Optional: true, 78 Computed: true, 79 }, 80 81 "source_security_group_id": &schema.Schema{ 82 Type: schema.TypeString, 83 Computed: true, 84 }, 85 86 "subnets": &schema.Schema{ 87 Type: schema.TypeSet, 88 Elem: &schema.Schema{Type: schema.TypeString}, 89 Optional: true, 90 Computed: true, 91 Set: schema.HashString, 92 }, 93 94 "idle_timeout": &schema.Schema{ 95 Type: schema.TypeInt, 96 Optional: true, 97 Default: 60, 98 }, 99 100 "connection_draining": &schema.Schema{ 101 Type: schema.TypeBool, 102 Optional: true, 103 Default: false, 104 }, 105 106 "connection_draining_timeout": &schema.Schema{ 107 Type: schema.TypeInt, 108 Optional: true, 109 Default: 300, 110 }, 111 112 "access_logs": &schema.Schema{ 113 Type: schema.TypeList, 114 Optional: true, 115 Elem: &schema.Resource{ 116 Schema: map[string]*schema.Schema{ 117 "interval": &schema.Schema{ 118 Type: schema.TypeInt, 119 Optional: true, 120 Default: 60, 121 }, 122 "bucket": &schema.Schema{ 123 Type: schema.TypeString, 124 Required: true, 125 }, 126 "bucket_prefix": &schema.Schema{ 127 Type: schema.TypeString, 128 Optional: true, 129 }, 130 }, 131 }, 132 }, 133 134 "listener": &schema.Schema{ 135 Type: schema.TypeSet, 136 Required: true, 137 Elem: &schema.Resource{ 138 Schema: map[string]*schema.Schema{ 139 "instance_port": &schema.Schema{ 140 Type: schema.TypeInt, 141 Required: true, 142 }, 143 144 "instance_protocol": &schema.Schema{ 145 Type: schema.TypeString, 146 Required: true, 147 }, 148 149 "lb_port": &schema.Schema{ 150 Type: schema.TypeInt, 151 Required: true, 152 }, 153 154 "lb_protocol": &schema.Schema{ 155 Type: schema.TypeString, 156 Required: true, 157 }, 158 159 "ssl_certificate_id": &schema.Schema{ 160 Type: schema.TypeString, 161 Optional: true, 162 }, 163 }, 164 }, 165 Set: resourceAwsElbListenerHash, 166 }, 167 168 "health_check": &schema.Schema{ 169 Type: schema.TypeList, 170 Optional: true, 171 Computed: true, 172 MaxItems: 1, 173 Elem: &schema.Resource{ 174 Schema: map[string]*schema.Schema{ 175 "healthy_threshold": &schema.Schema{ 176 Type: schema.TypeInt, 177 Required: true, 178 }, 179 180 "unhealthy_threshold": &schema.Schema{ 181 Type: schema.TypeInt, 182 Required: true, 183 }, 184 185 "target": &schema.Schema{ 186 Type: schema.TypeString, 187 Required: true, 188 }, 189 190 "interval": &schema.Schema{ 191 Type: schema.TypeInt, 192 Required: true, 193 }, 194 195 "timeout": &schema.Schema{ 196 Type: schema.TypeInt, 197 Required: true, 198 }, 199 }, 200 }, 201 }, 202 203 "dns_name": &schema.Schema{ 204 Type: schema.TypeString, 205 Computed: true, 206 }, 207 208 "zone_id": &schema.Schema{ 209 Type: schema.TypeString, 210 Computed: true, 211 }, 212 213 "tags": tagsSchema(), 214 }, 215 } 216 } 217 218 func resourceAwsElbCreate(d *schema.ResourceData, meta interface{}) error { 219 elbconn := meta.(*AWSClient).elbconn 220 221 // Expand the "listener" set to aws-sdk-go compat []*elb.Listener 222 listeners, err := expandListeners(d.Get("listener").(*schema.Set).List()) 223 if err != nil { 224 return err 225 } 226 227 var elbName string 228 if v, ok := d.GetOk("name"); ok { 229 elbName = v.(string) 230 } else { 231 elbName = resource.PrefixedUniqueId("tf-lb-") 232 d.Set("name", elbName) 233 } 234 235 tags := tagsFromMapELB(d.Get("tags").(map[string]interface{})) 236 // Provision the elb 237 elbOpts := &elb.CreateLoadBalancerInput{ 238 LoadBalancerName: aws.String(elbName), 239 Listeners: listeners, 240 Tags: tags, 241 } 242 243 if scheme, ok := d.GetOk("internal"); ok && scheme.(bool) { 244 elbOpts.Scheme = aws.String("internal") 245 } 246 247 if v, ok := d.GetOk("availability_zones"); ok { 248 elbOpts.AvailabilityZones = expandStringList(v.(*schema.Set).List()) 249 } 250 251 if v, ok := d.GetOk("security_groups"); ok { 252 elbOpts.SecurityGroups = expandStringList(v.(*schema.Set).List()) 253 } 254 255 if v, ok := d.GetOk("subnets"); ok { 256 elbOpts.Subnets = expandStringList(v.(*schema.Set).List()) 257 } 258 259 log.Printf("[DEBUG] ELB create configuration: %#v", elbOpts) 260 err = resource.Retry(1*time.Minute, func() *resource.RetryError { 261 _, err := elbconn.CreateLoadBalancer(elbOpts) 262 263 if err != nil { 264 if awsErr, ok := err.(awserr.Error); ok { 265 // Check for IAM SSL Cert error, eventual consistancy issue 266 if awsErr.Code() == "CertificateNotFound" { 267 return resource.RetryableError( 268 fmt.Errorf("[WARN] Error creating ELB Listener with SSL Cert, retrying: %s", err)) 269 } 270 } 271 return resource.NonRetryableError(err) 272 } 273 return nil 274 }) 275 276 if err != nil { 277 return err 278 } 279 280 // Assign the elb's unique identifier for use later 281 d.SetId(elbName) 282 log.Printf("[INFO] ELB ID: %s", d.Id()) 283 284 // Enable partial mode and record what we set 285 d.Partial(true) 286 d.SetPartial("name") 287 d.SetPartial("internal") 288 d.SetPartial("availability_zones") 289 d.SetPartial("listener") 290 d.SetPartial("security_groups") 291 d.SetPartial("subnets") 292 293 d.Set("tags", tagsToMapELB(tags)) 294 295 return resourceAwsElbUpdate(d, meta) 296 } 297 298 func resourceAwsElbRead(d *schema.ResourceData, meta interface{}) error { 299 elbconn := meta.(*AWSClient).elbconn 300 elbName := d.Id() 301 302 // Retrieve the ELB properties for updating the state 303 describeElbOpts := &elb.DescribeLoadBalancersInput{ 304 LoadBalancerNames: []*string{aws.String(elbName)}, 305 } 306 307 describeResp, err := elbconn.DescribeLoadBalancers(describeElbOpts) 308 if err != nil { 309 if isLoadBalancerNotFound(err) { 310 // The ELB is gone now, so just remove it from the state 311 d.SetId("") 312 return nil 313 } 314 315 return fmt.Errorf("Error retrieving ELB: %s", err) 316 } 317 if len(describeResp.LoadBalancerDescriptions) != 1 { 318 return fmt.Errorf("Unable to find ELB: %#v", describeResp.LoadBalancerDescriptions) 319 } 320 321 describeAttrsOpts := &elb.DescribeLoadBalancerAttributesInput{ 322 LoadBalancerName: aws.String(elbName), 323 } 324 describeAttrsResp, err := elbconn.DescribeLoadBalancerAttributes(describeAttrsOpts) 325 if err != nil { 326 if isLoadBalancerNotFound(err) { 327 // The ELB is gone now, so just remove it from the state 328 d.SetId("") 329 return nil 330 } 331 332 return fmt.Errorf("Error retrieving ELB: %s", err) 333 } 334 335 lbAttrs := describeAttrsResp.LoadBalancerAttributes 336 337 lb := describeResp.LoadBalancerDescriptions[0] 338 339 d.Set("name", *lb.LoadBalancerName) 340 d.Set("dns_name", *lb.DNSName) 341 d.Set("zone_id", *lb.CanonicalHostedZoneNameID) 342 d.Set("internal", *lb.Scheme == "internal") 343 d.Set("availability_zones", flattenStringList(lb.AvailabilityZones)) 344 d.Set("instances", flattenInstances(lb.Instances)) 345 d.Set("listener", flattenListeners(lb.ListenerDescriptions)) 346 d.Set("security_groups", flattenStringList(lb.SecurityGroups)) 347 if lb.SourceSecurityGroup != nil { 348 group := lb.SourceSecurityGroup.GroupName 349 if lb.SourceSecurityGroup.OwnerAlias != nil && *lb.SourceSecurityGroup.OwnerAlias != "" { 350 group = aws.String(*lb.SourceSecurityGroup.OwnerAlias + "/" + *lb.SourceSecurityGroup.GroupName) 351 } 352 d.Set("source_security_group", group) 353 354 // Manually look up the ELB Security Group ID, since it's not provided 355 var elbVpc string 356 if lb.VPCId != nil { 357 elbVpc = *lb.VPCId 358 sgId, err := sourceSGIdByName(meta, *lb.SourceSecurityGroup.GroupName, elbVpc) 359 if err != nil { 360 return fmt.Errorf("[WARN] Error looking up ELB Security Group ID: %s", err) 361 } else { 362 d.Set("source_security_group_id", sgId) 363 } 364 } 365 } 366 d.Set("subnets", flattenStringList(lb.Subnets)) 367 d.Set("idle_timeout", lbAttrs.ConnectionSettings.IdleTimeout) 368 d.Set("connection_draining", lbAttrs.ConnectionDraining.Enabled) 369 d.Set("connection_draining_timeout", lbAttrs.ConnectionDraining.Timeout) 370 d.Set("cross_zone_load_balancing", lbAttrs.CrossZoneLoadBalancing.Enabled) 371 if lbAttrs.AccessLog != nil { 372 if err := d.Set("access_logs", flattenAccessLog(lbAttrs.AccessLog)); err != nil { 373 return err 374 } 375 } 376 377 resp, err := elbconn.DescribeTags(&elb.DescribeTagsInput{ 378 LoadBalancerNames: []*string{lb.LoadBalancerName}, 379 }) 380 381 var et []*elb.Tag 382 if len(resp.TagDescriptions) > 0 { 383 et = resp.TagDescriptions[0].Tags 384 } 385 d.Set("tags", tagsToMapELB(et)) 386 387 // There's only one health check, so save that to state as we 388 // currently can 389 if *lb.HealthCheck.Target != "" { 390 d.Set("health_check", flattenHealthCheck(lb.HealthCheck)) 391 } 392 393 return nil 394 } 395 396 func resourceAwsElbUpdate(d *schema.ResourceData, meta interface{}) error { 397 elbconn := meta.(*AWSClient).elbconn 398 399 d.Partial(true) 400 401 if d.HasChange("listener") { 402 o, n := d.GetChange("listener") 403 os := o.(*schema.Set) 404 ns := n.(*schema.Set) 405 406 remove, _ := expandListeners(os.Difference(ns).List()) 407 add, _ := expandListeners(ns.Difference(os).List()) 408 409 if len(remove) > 0 { 410 ports := make([]*int64, 0, len(remove)) 411 for _, listener := range remove { 412 ports = append(ports, listener.LoadBalancerPort) 413 } 414 415 deleteListenersOpts := &elb.DeleteLoadBalancerListenersInput{ 416 LoadBalancerName: aws.String(d.Id()), 417 LoadBalancerPorts: ports, 418 } 419 420 log.Printf("[DEBUG] ELB Delete Listeners opts: %s", deleteListenersOpts) 421 _, err := elbconn.DeleteLoadBalancerListeners(deleteListenersOpts) 422 if err != nil { 423 return fmt.Errorf("Failure removing outdated ELB listeners: %s", err) 424 } 425 } 426 427 if len(add) > 0 { 428 createListenersOpts := &elb.CreateLoadBalancerListenersInput{ 429 LoadBalancerName: aws.String(d.Id()), 430 Listeners: add, 431 } 432 433 // Occasionally AWS will error with a 'duplicate listener', without any 434 // other listeners on the ELB. Retry here to eliminate that. 435 err := resource.Retry(1*time.Minute, func() *resource.RetryError { 436 log.Printf("[DEBUG] ELB Create Listeners opts: %s", createListenersOpts) 437 if _, err := elbconn.CreateLoadBalancerListeners(createListenersOpts); err != nil { 438 if awsErr, ok := err.(awserr.Error); ok { 439 if awsErr.Code() == "DuplicateListener" { 440 log.Printf("[DEBUG] Duplicate listener found for ELB (%s), retrying", d.Id()) 441 return resource.RetryableError(awsErr) 442 } 443 if awsErr.Code() == "CertificateNotFound" && strings.Contains(awsErr.Message(), "Server Certificate not found for the key: arn") { 444 log.Printf("[DEBUG] SSL Cert not found for given ARN, retrying") 445 return resource.RetryableError(awsErr) 446 } 447 } 448 449 // Didn't recognize the error, so shouldn't retry. 450 return resource.NonRetryableError(err) 451 } 452 // Successful creation 453 return nil 454 }) 455 if err != nil { 456 return fmt.Errorf("Failure adding new or updated ELB listeners: %s", err) 457 } 458 } 459 460 d.SetPartial("listener") 461 } 462 463 // If we currently have instances, or did have instances, 464 // we want to figure out what to add and remove from the load 465 // balancer 466 if d.HasChange("instances") { 467 o, n := d.GetChange("instances") 468 os := o.(*schema.Set) 469 ns := n.(*schema.Set) 470 remove := expandInstanceString(os.Difference(ns).List()) 471 add := expandInstanceString(ns.Difference(os).List()) 472 473 if len(add) > 0 { 474 registerInstancesOpts := elb.RegisterInstancesWithLoadBalancerInput{ 475 LoadBalancerName: aws.String(d.Id()), 476 Instances: add, 477 } 478 479 _, err := elbconn.RegisterInstancesWithLoadBalancer(®isterInstancesOpts) 480 if err != nil { 481 return fmt.Errorf("Failure registering instances with ELB: %s", err) 482 } 483 } 484 if len(remove) > 0 { 485 deRegisterInstancesOpts := elb.DeregisterInstancesFromLoadBalancerInput{ 486 LoadBalancerName: aws.String(d.Id()), 487 Instances: remove, 488 } 489 490 _, err := elbconn.DeregisterInstancesFromLoadBalancer(&deRegisterInstancesOpts) 491 if err != nil { 492 return fmt.Errorf("Failure deregistering instances from ELB: %s", err) 493 } 494 } 495 496 d.SetPartial("instances") 497 } 498 499 if d.HasChange("cross_zone_load_balancing") || d.HasChange("idle_timeout") || d.HasChange("access_logs") { 500 attrs := elb.ModifyLoadBalancerAttributesInput{ 501 LoadBalancerName: aws.String(d.Get("name").(string)), 502 LoadBalancerAttributes: &elb.LoadBalancerAttributes{ 503 CrossZoneLoadBalancing: &elb.CrossZoneLoadBalancing{ 504 Enabled: aws.Bool(d.Get("cross_zone_load_balancing").(bool)), 505 }, 506 ConnectionSettings: &elb.ConnectionSettings{ 507 IdleTimeout: aws.Int64(int64(d.Get("idle_timeout").(int))), 508 }, 509 }, 510 } 511 512 logs := d.Get("access_logs").([]interface{}) 513 if len(logs) > 1 { 514 return fmt.Errorf("Only one access logs config per ELB is supported") 515 } else if len(logs) == 1 { 516 log := logs[0].(map[string]interface{}) 517 accessLog := &elb.AccessLog{ 518 Enabled: aws.Bool(true), 519 EmitInterval: aws.Int64(int64(log["interval"].(int))), 520 S3BucketName: aws.String(log["bucket"].(string)), 521 } 522 523 if log["bucket_prefix"] != "" { 524 accessLog.S3BucketPrefix = aws.String(log["bucket_prefix"].(string)) 525 } 526 527 attrs.LoadBalancerAttributes.AccessLog = accessLog 528 } else if len(logs) == 0 { 529 // disable access logs 530 attrs.LoadBalancerAttributes.AccessLog = &elb.AccessLog{ 531 Enabled: aws.Bool(false), 532 } 533 } 534 535 log.Printf("[DEBUG] ELB Modify Load Balancer Attributes Request: %#v", attrs) 536 _, err := elbconn.ModifyLoadBalancerAttributes(&attrs) 537 if err != nil { 538 return fmt.Errorf("Failure configuring ELB attributes: %s", err) 539 } 540 541 d.SetPartial("cross_zone_load_balancing") 542 d.SetPartial("idle_timeout") 543 d.SetPartial("connection_draining_timeout") 544 } 545 546 // We have to do these changes separately from everything else since 547 // they have some weird undocumented rules. You can't set the timeout 548 // without having connection draining to true, so we set that to true, 549 // set the timeout, then reset it to false if requested. 550 if d.HasChange("connection_draining") || d.HasChange("connection_draining_timeout") { 551 // We do timeout changes first since they require us to set draining 552 // to true for a hot second. 553 if d.HasChange("connection_draining_timeout") { 554 attrs := elb.ModifyLoadBalancerAttributesInput{ 555 LoadBalancerName: aws.String(d.Get("name").(string)), 556 LoadBalancerAttributes: &elb.LoadBalancerAttributes{ 557 ConnectionDraining: &elb.ConnectionDraining{ 558 Enabled: aws.Bool(true), 559 Timeout: aws.Int64(int64(d.Get("connection_draining_timeout").(int))), 560 }, 561 }, 562 } 563 564 _, err := elbconn.ModifyLoadBalancerAttributes(&attrs) 565 if err != nil { 566 return fmt.Errorf("Failure configuring ELB attributes: %s", err) 567 } 568 569 d.SetPartial("connection_draining_timeout") 570 } 571 572 // Then we always set connection draining even if there is no change. 573 // This lets us reset to "false" if requested even with a timeout 574 // change. 575 attrs := elb.ModifyLoadBalancerAttributesInput{ 576 LoadBalancerName: aws.String(d.Get("name").(string)), 577 LoadBalancerAttributes: &elb.LoadBalancerAttributes{ 578 ConnectionDraining: &elb.ConnectionDraining{ 579 Enabled: aws.Bool(d.Get("connection_draining").(bool)), 580 }, 581 }, 582 } 583 584 _, err := elbconn.ModifyLoadBalancerAttributes(&attrs) 585 if err != nil { 586 return fmt.Errorf("Failure configuring ELB attributes: %s", err) 587 } 588 589 d.SetPartial("connection_draining") 590 } 591 592 if d.HasChange("health_check") { 593 hc := d.Get("health_check").([]interface{}) 594 if len(hc) > 0 { 595 check := hc[0].(map[string]interface{}) 596 configureHealthCheckOpts := elb.ConfigureHealthCheckInput{ 597 LoadBalancerName: aws.String(d.Id()), 598 HealthCheck: &elb.HealthCheck{ 599 HealthyThreshold: aws.Int64(int64(check["healthy_threshold"].(int))), 600 UnhealthyThreshold: aws.Int64(int64(check["unhealthy_threshold"].(int))), 601 Interval: aws.Int64(int64(check["interval"].(int))), 602 Target: aws.String(check["target"].(string)), 603 Timeout: aws.Int64(int64(check["timeout"].(int))), 604 }, 605 } 606 _, err := elbconn.ConfigureHealthCheck(&configureHealthCheckOpts) 607 if err != nil { 608 return fmt.Errorf("Failure configuring health check for ELB: %s", err) 609 } 610 d.SetPartial("health_check") 611 } 612 } 613 614 if d.HasChange("security_groups") { 615 groups := d.Get("security_groups").(*schema.Set).List() 616 617 applySecurityGroupsOpts := elb.ApplySecurityGroupsToLoadBalancerInput{ 618 LoadBalancerName: aws.String(d.Id()), 619 SecurityGroups: expandStringList(groups), 620 } 621 622 _, err := elbconn.ApplySecurityGroupsToLoadBalancer(&applySecurityGroupsOpts) 623 if err != nil { 624 return fmt.Errorf("Failure applying security groups to ELB: %s", err) 625 } 626 627 d.SetPartial("security_groups") 628 } 629 630 if d.HasChange("availability_zones") { 631 o, n := d.GetChange("availability_zones") 632 os := o.(*schema.Set) 633 ns := n.(*schema.Set) 634 635 removed := expandStringList(os.Difference(ns).List()) 636 added := expandStringList(ns.Difference(os).List()) 637 638 if len(added) > 0 { 639 enableOpts := &elb.EnableAvailabilityZonesForLoadBalancerInput{ 640 LoadBalancerName: aws.String(d.Id()), 641 AvailabilityZones: added, 642 } 643 644 log.Printf("[DEBUG] ELB enable availability zones opts: %s", enableOpts) 645 _, err := elbconn.EnableAvailabilityZonesForLoadBalancer(enableOpts) 646 if err != nil { 647 return fmt.Errorf("Failure enabling ELB availability zones: %s", err) 648 } 649 } 650 651 if len(removed) > 0 { 652 disableOpts := &elb.DisableAvailabilityZonesForLoadBalancerInput{ 653 LoadBalancerName: aws.String(d.Id()), 654 AvailabilityZones: removed, 655 } 656 657 log.Printf("[DEBUG] ELB disable availability zones opts: %s", disableOpts) 658 _, err := elbconn.DisableAvailabilityZonesForLoadBalancer(disableOpts) 659 if err != nil { 660 return fmt.Errorf("Failure disabling ELB availability zones: %s", err) 661 } 662 } 663 664 d.SetPartial("availability_zones") 665 } 666 667 if d.HasChange("subnets") { 668 o, n := d.GetChange("subnets") 669 os := o.(*schema.Set) 670 ns := n.(*schema.Set) 671 672 removed := expandStringList(os.Difference(ns).List()) 673 added := expandStringList(ns.Difference(os).List()) 674 675 if len(added) > 0 { 676 attachOpts := &elb.AttachLoadBalancerToSubnetsInput{ 677 LoadBalancerName: aws.String(d.Id()), 678 Subnets: added, 679 } 680 681 log.Printf("[DEBUG] ELB attach subnets opts: %s", attachOpts) 682 _, err := elbconn.AttachLoadBalancerToSubnets(attachOpts) 683 if err != nil { 684 return fmt.Errorf("Failure adding ELB subnets: %s", err) 685 } 686 } 687 688 if len(removed) > 0 { 689 detachOpts := &elb.DetachLoadBalancerFromSubnetsInput{ 690 LoadBalancerName: aws.String(d.Id()), 691 Subnets: removed, 692 } 693 694 log.Printf("[DEBUG] ELB detach subnets opts: %s", detachOpts) 695 _, err := elbconn.DetachLoadBalancerFromSubnets(detachOpts) 696 if err != nil { 697 return fmt.Errorf("Failure removing ELB subnets: %s", err) 698 } 699 } 700 701 d.SetPartial("subnets") 702 } 703 704 if err := setTagsELB(elbconn, d); err != nil { 705 return err 706 } 707 708 d.SetPartial("tags") 709 d.Partial(false) 710 711 return resourceAwsElbRead(d, meta) 712 } 713 714 func resourceAwsElbDelete(d *schema.ResourceData, meta interface{}) error { 715 elbconn := meta.(*AWSClient).elbconn 716 717 log.Printf("[INFO] Deleting ELB: %s", d.Id()) 718 719 // Destroy the load balancer 720 deleteElbOpts := elb.DeleteLoadBalancerInput{ 721 LoadBalancerName: aws.String(d.Id()), 722 } 723 if _, err := elbconn.DeleteLoadBalancer(&deleteElbOpts); err != nil { 724 return fmt.Errorf("Error deleting ELB: %s", err) 725 } 726 727 return nil 728 } 729 730 func resourceAwsElbListenerHash(v interface{}) int { 731 var buf bytes.Buffer 732 m := v.(map[string]interface{}) 733 buf.WriteString(fmt.Sprintf("%d-", m["instance_port"].(int))) 734 buf.WriteString(fmt.Sprintf("%s-", 735 strings.ToLower(m["instance_protocol"].(string)))) 736 buf.WriteString(fmt.Sprintf("%d-", m["lb_port"].(int))) 737 buf.WriteString(fmt.Sprintf("%s-", 738 strings.ToLower(m["lb_protocol"].(string)))) 739 740 if v, ok := m["ssl_certificate_id"]; ok { 741 buf.WriteString(fmt.Sprintf("%s-", v.(string))) 742 } 743 744 return hashcode.String(buf.String()) 745 } 746 747 func isLoadBalancerNotFound(err error) bool { 748 elberr, ok := err.(awserr.Error) 749 return ok && elberr.Code() == "LoadBalancerNotFound" 750 } 751 752 func sourceSGIdByName(meta interface{}, sg, vpcId string) (string, error) { 753 conn := meta.(*AWSClient).ec2conn 754 var filters []*ec2.Filter 755 var sgFilterName, sgFilterVPCID *ec2.Filter 756 sgFilterName = &ec2.Filter{ 757 Name: aws.String("group-name"), 758 Values: []*string{aws.String(sg)}, 759 } 760 761 if vpcId != "" { 762 sgFilterVPCID = &ec2.Filter{ 763 Name: aws.String("vpc-id"), 764 Values: []*string{aws.String(vpcId)}, 765 } 766 } 767 768 filters = append(filters, sgFilterName) 769 770 if sgFilterVPCID != nil { 771 filters = append(filters, sgFilterVPCID) 772 } 773 774 req := &ec2.DescribeSecurityGroupsInput{ 775 Filters: filters, 776 } 777 resp, err := conn.DescribeSecurityGroups(req) 778 if err != nil { 779 if ec2err, ok := err.(awserr.Error); ok { 780 if ec2err.Code() == "InvalidSecurityGroupID.NotFound" || 781 ec2err.Code() == "InvalidGroup.NotFound" { 782 resp = nil 783 err = nil 784 } 785 } 786 787 if err != nil { 788 log.Printf("Error on ELB SG look up: %s", err) 789 return "", err 790 } 791 } 792 793 if resp == nil || len(resp.SecurityGroups) == 0 { 794 return "", fmt.Errorf("No security groups found for name %s and vpc id %s", sg, vpcId) 795 } 796 797 group := resp.SecurityGroups[0] 798 return *group.GroupId, nil 799 }