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