github.com/leeprovoost/terraform@v0.6.10-0.20160119085442-96f3f76118e7/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.TypeSet,
   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  				Set: resourceAwsElbHealthCheckHash,
   198  			},
   199  
   200  			"dns_name": &schema.Schema{
   201  				Type:     schema.TypeString,
   202  				Computed: true,
   203  			},
   204  
   205  			"zone_id": &schema.Schema{
   206  				Type:     schema.TypeString,
   207  				Computed: true,
   208  			},
   209  
   210  			"tags": tagsSchema(),
   211  		},
   212  	}
   213  }
   214  
   215  func resourceAwsElbCreate(d *schema.ResourceData, meta interface{}) error {
   216  	elbconn := meta.(*AWSClient).elbconn
   217  
   218  	// Expand the "listener" set to aws-sdk-go compat []*elb.Listener
   219  	listeners, err := expandListeners(d.Get("listener").(*schema.Set).List())
   220  	if err != nil {
   221  		return err
   222  	}
   223  
   224  	var elbName string
   225  	if v, ok := d.GetOk("name"); ok {
   226  		elbName = v.(string)
   227  	} else {
   228  		elbName = resource.PrefixedUniqueId("tf-lb-")
   229  		d.Set("name", elbName)
   230  	}
   231  
   232  	tags := tagsFromMapELB(d.Get("tags").(map[string]interface{}))
   233  	// Provision the elb
   234  	elbOpts := &elb.CreateLoadBalancerInput{
   235  		LoadBalancerName: aws.String(elbName),
   236  		Listeners:        listeners,
   237  		Tags:             tags,
   238  	}
   239  
   240  	if scheme, ok := d.GetOk("internal"); ok && scheme.(bool) {
   241  		elbOpts.Scheme = aws.String("internal")
   242  	}
   243  
   244  	if v, ok := d.GetOk("availability_zones"); ok {
   245  		elbOpts.AvailabilityZones = expandStringList(v.(*schema.Set).List())
   246  	}
   247  
   248  	if v, ok := d.GetOk("security_groups"); ok {
   249  		elbOpts.SecurityGroups = expandStringList(v.(*schema.Set).List())
   250  	}
   251  
   252  	if v, ok := d.GetOk("subnets"); ok {
   253  		elbOpts.Subnets = expandStringList(v.(*schema.Set).List())
   254  	}
   255  
   256  	log.Printf("[DEBUG] ELB create configuration: %#v", elbOpts)
   257  	err = resource.Retry(1*time.Minute, func() error {
   258  		_, err := elbconn.CreateLoadBalancer(elbOpts)
   259  
   260  		if err != nil {
   261  			if awsErr, ok := err.(awserr.Error); ok {
   262  				// Check for IAM SSL Cert error, eventual consistancy issue
   263  				if awsErr.Code() == "CertificateNotFound" {
   264  					return fmt.Errorf("[WARN] Error creating ELB Listener with SSL Cert, retrying: %s", err)
   265  				}
   266  			}
   267  			return resource.RetryError{Err: err}
   268  		}
   269  		return nil
   270  	})
   271  
   272  	if err != nil {
   273  		return err
   274  	}
   275  
   276  	// Assign the elb's unique identifier for use later
   277  	d.SetId(elbName)
   278  	log.Printf("[INFO] ELB ID: %s", d.Id())
   279  
   280  	// Enable partial mode and record what we set
   281  	d.Partial(true)
   282  	d.SetPartial("name")
   283  	d.SetPartial("internal")
   284  	d.SetPartial("availability_zones")
   285  	d.SetPartial("listener")
   286  	d.SetPartial("security_groups")
   287  	d.SetPartial("subnets")
   288  
   289  	d.Set("tags", tagsToMapELB(tags))
   290  
   291  	return resourceAwsElbUpdate(d, meta)
   292  }
   293  
   294  func resourceAwsElbRead(d *schema.ResourceData, meta interface{}) error {
   295  	elbconn := meta.(*AWSClient).elbconn
   296  	elbName := d.Id()
   297  
   298  	// Retrieve the ELB properties for updating the state
   299  	describeElbOpts := &elb.DescribeLoadBalancersInput{
   300  		LoadBalancerNames: []*string{aws.String(elbName)},
   301  	}
   302  
   303  	describeResp, err := elbconn.DescribeLoadBalancers(describeElbOpts)
   304  	if err != nil {
   305  		if isLoadBalancerNotFound(err) {
   306  			// The ELB is gone now, so just remove it from the state
   307  			d.SetId("")
   308  			return nil
   309  		}
   310  
   311  		return fmt.Errorf("Error retrieving ELB: %s", err)
   312  	}
   313  	if len(describeResp.LoadBalancerDescriptions) != 1 {
   314  		return fmt.Errorf("Unable to find ELB: %#v", describeResp.LoadBalancerDescriptions)
   315  	}
   316  
   317  	describeAttrsOpts := &elb.DescribeLoadBalancerAttributesInput{
   318  		LoadBalancerName: aws.String(elbName),
   319  	}
   320  	describeAttrsResp, err := elbconn.DescribeLoadBalancerAttributes(describeAttrsOpts)
   321  	if err != nil {
   322  		if isLoadBalancerNotFound(err) {
   323  			// The ELB is gone now, so just remove it from the state
   324  			d.SetId("")
   325  			return nil
   326  		}
   327  
   328  		return fmt.Errorf("Error retrieving ELB: %s", err)
   329  	}
   330  
   331  	lbAttrs := describeAttrsResp.LoadBalancerAttributes
   332  
   333  	lb := describeResp.LoadBalancerDescriptions[0]
   334  
   335  	d.Set("name", *lb.LoadBalancerName)
   336  	d.Set("dns_name", *lb.DNSName)
   337  	d.Set("zone_id", *lb.CanonicalHostedZoneNameID)
   338  	d.Set("internal", *lb.Scheme == "internal")
   339  	d.Set("availability_zones", flattenStringList(lb.AvailabilityZones))
   340  	d.Set("instances", flattenInstances(lb.Instances))
   341  	d.Set("listener", flattenListeners(lb.ListenerDescriptions))
   342  	d.Set("security_groups", flattenStringList(lb.SecurityGroups))
   343  	if lb.SourceSecurityGroup != nil {
   344  		d.Set("source_security_group", lb.SourceSecurityGroup.GroupName)
   345  
   346  		// Manually look up the ELB Security Group ID, since it's not provided
   347  		var elbVpc string
   348  		if lb.VPCId != nil {
   349  			elbVpc = *lb.VPCId
   350  			sgId, err := sourceSGIdByName(meta, *lb.SourceSecurityGroup.GroupName, elbVpc)
   351  			if err != nil {
   352  				return fmt.Errorf("[WARN] Error looking up ELB Security Group ID: %s", err)
   353  			} else {
   354  				d.Set("source_security_group_id", sgId)
   355  			}
   356  		}
   357  	}
   358  	d.Set("subnets", flattenStringList(lb.Subnets))
   359  	d.Set("idle_timeout", lbAttrs.ConnectionSettings.IdleTimeout)
   360  	d.Set("connection_draining", lbAttrs.ConnectionDraining.Enabled)
   361  	d.Set("connection_draining_timeout", lbAttrs.ConnectionDraining.Timeout)
   362  	if lbAttrs.AccessLog != nil {
   363  		if err := d.Set("access_logs", flattenAccessLog(lbAttrs.AccessLog)); err != nil {
   364  			return err
   365  		}
   366  	}
   367  
   368  	resp, err := elbconn.DescribeTags(&elb.DescribeTagsInput{
   369  		LoadBalancerNames: []*string{lb.LoadBalancerName},
   370  	})
   371  
   372  	var et []*elb.Tag
   373  	if len(resp.TagDescriptions) > 0 {
   374  		et = resp.TagDescriptions[0].Tags
   375  	}
   376  	d.Set("tags", tagsToMapELB(et))
   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  			log.Printf("[DEBUG] ELB Create Listeners opts: %s", createListenersOpts)
   424  			_, err := elbconn.CreateLoadBalancerListeners(createListenersOpts)
   425  			if err != nil {
   426  				return fmt.Errorf("Failure adding new or updated ELB listeners: %s", err)
   427  			}
   428  		}
   429  
   430  		d.SetPartial("listener")
   431  	}
   432  
   433  	// If we currently have instances, or did have instances,
   434  	// we want to figure out what to add and remove from the load
   435  	// balancer
   436  	if d.HasChange("instances") {
   437  		o, n := d.GetChange("instances")
   438  		os := o.(*schema.Set)
   439  		ns := n.(*schema.Set)
   440  		remove := expandInstanceString(os.Difference(ns).List())
   441  		add := expandInstanceString(ns.Difference(os).List())
   442  
   443  		if len(add) > 0 {
   444  			registerInstancesOpts := elb.RegisterInstancesWithLoadBalancerInput{
   445  				LoadBalancerName: aws.String(d.Id()),
   446  				Instances:        add,
   447  			}
   448  
   449  			_, err := elbconn.RegisterInstancesWithLoadBalancer(&registerInstancesOpts)
   450  			if err != nil {
   451  				return fmt.Errorf("Failure registering instances with ELB: %s", err)
   452  			}
   453  		}
   454  		if len(remove) > 0 {
   455  			deRegisterInstancesOpts := elb.DeregisterInstancesFromLoadBalancerInput{
   456  				LoadBalancerName: aws.String(d.Id()),
   457  				Instances:        remove,
   458  			}
   459  
   460  			_, err := elbconn.DeregisterInstancesFromLoadBalancer(&deRegisterInstancesOpts)
   461  			if err != nil {
   462  				return fmt.Errorf("Failure deregistering instances from ELB: %s", err)
   463  			}
   464  		}
   465  
   466  		d.SetPartial("instances")
   467  	}
   468  
   469  	if d.HasChange("cross_zone_load_balancing") || d.HasChange("idle_timeout") || d.HasChange("access_logs") {
   470  		attrs := elb.ModifyLoadBalancerAttributesInput{
   471  			LoadBalancerName: aws.String(d.Get("name").(string)),
   472  			LoadBalancerAttributes: &elb.LoadBalancerAttributes{
   473  				CrossZoneLoadBalancing: &elb.CrossZoneLoadBalancing{
   474  					Enabled: aws.Bool(d.Get("cross_zone_load_balancing").(bool)),
   475  				},
   476  				ConnectionSettings: &elb.ConnectionSettings{
   477  					IdleTimeout: aws.Int64(int64(d.Get("idle_timeout").(int))),
   478  				},
   479  			},
   480  		}
   481  
   482  		logs := d.Get("access_logs").(*schema.Set).List()
   483  		if len(logs) > 1 {
   484  			return fmt.Errorf("Only one access logs config per ELB is supported")
   485  		} else if len(logs) == 1 {
   486  			log := logs[0].(map[string]interface{})
   487  			accessLog := &elb.AccessLog{
   488  				Enabled:      aws.Bool(true),
   489  				EmitInterval: aws.Int64(int64(log["interval"].(int))),
   490  				S3BucketName: aws.String(log["bucket"].(string)),
   491  			}
   492  
   493  			if log["bucket_prefix"] != "" {
   494  				accessLog.S3BucketPrefix = aws.String(log["bucket_prefix"].(string))
   495  			}
   496  
   497  			attrs.LoadBalancerAttributes.AccessLog = accessLog
   498  		} else if len(logs) == 0 {
   499  			// disable access logs
   500  			attrs.LoadBalancerAttributes.AccessLog = &elb.AccessLog{
   501  				Enabled: aws.Bool(false),
   502  			}
   503  		}
   504  
   505  		log.Printf("[DEBUG] ELB Modify Load Balancer Attributes Request: %#v", attrs)
   506  		_, err := elbconn.ModifyLoadBalancerAttributes(&attrs)
   507  		if err != nil {
   508  			return fmt.Errorf("Failure configuring ELB attributes: %s", err)
   509  		}
   510  
   511  		d.SetPartial("cross_zone_load_balancing")
   512  		d.SetPartial("idle_timeout")
   513  		d.SetPartial("connection_draining_timeout")
   514  	}
   515  
   516  	// We have to do these changes separately from everything else since
   517  	// they have some weird undocumented rules. You can't set the timeout
   518  	// without having connection draining to true, so we set that to true,
   519  	// set the timeout, then reset it to false if requested.
   520  	if d.HasChange("connection_draining") || d.HasChange("connection_draining_timeout") {
   521  		// We do timeout changes first since they require us to set draining
   522  		// to true for a hot second.
   523  		if d.HasChange("connection_draining_timeout") {
   524  			attrs := elb.ModifyLoadBalancerAttributesInput{
   525  				LoadBalancerName: aws.String(d.Get("name").(string)),
   526  				LoadBalancerAttributes: &elb.LoadBalancerAttributes{
   527  					ConnectionDraining: &elb.ConnectionDraining{
   528  						Enabled: aws.Bool(true),
   529  						Timeout: aws.Int64(int64(d.Get("connection_draining_timeout").(int))),
   530  					},
   531  				},
   532  			}
   533  
   534  			_, err := elbconn.ModifyLoadBalancerAttributes(&attrs)
   535  			if err != nil {
   536  				return fmt.Errorf("Failure configuring ELB attributes: %s", err)
   537  			}
   538  
   539  			d.SetPartial("connection_draining_timeout")
   540  		}
   541  
   542  		// Then we always set connection draining even if there is no change.
   543  		// This lets us reset to "false" if requested even with a timeout
   544  		// change.
   545  		attrs := elb.ModifyLoadBalancerAttributesInput{
   546  			LoadBalancerName: aws.String(d.Get("name").(string)),
   547  			LoadBalancerAttributes: &elb.LoadBalancerAttributes{
   548  				ConnectionDraining: &elb.ConnectionDraining{
   549  					Enabled: aws.Bool(d.Get("connection_draining").(bool)),
   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")
   560  	}
   561  
   562  	if d.HasChange("health_check") {
   563  		vs := d.Get("health_check").(*schema.Set).List()
   564  		if len(vs) > 0 {
   565  			check := vs[0].(map[string]interface{})
   566  			configureHealthCheckOpts := elb.ConfigureHealthCheckInput{
   567  				LoadBalancerName: aws.String(d.Id()),
   568  				HealthCheck: &elb.HealthCheck{
   569  					HealthyThreshold:   aws.Int64(int64(check["healthy_threshold"].(int))),
   570  					UnhealthyThreshold: aws.Int64(int64(check["unhealthy_threshold"].(int))),
   571  					Interval:           aws.Int64(int64(check["interval"].(int))),
   572  					Target:             aws.String(check["target"].(string)),
   573  					Timeout:            aws.Int64(int64(check["timeout"].(int))),
   574  				},
   575  			}
   576  			_, err := elbconn.ConfigureHealthCheck(&configureHealthCheckOpts)
   577  			if err != nil {
   578  				return fmt.Errorf("Failure configuring health check for ELB: %s", err)
   579  			}
   580  			d.SetPartial("health_check")
   581  		}
   582  	}
   583  
   584  	if d.HasChange("security_groups") {
   585  		groups := d.Get("security_groups").(*schema.Set).List()
   586  
   587  		applySecurityGroupsOpts := elb.ApplySecurityGroupsToLoadBalancerInput{
   588  			LoadBalancerName: aws.String(d.Id()),
   589  			SecurityGroups:   expandStringList(groups),
   590  		}
   591  
   592  		_, err := elbconn.ApplySecurityGroupsToLoadBalancer(&applySecurityGroupsOpts)
   593  		if err != nil {
   594  			return fmt.Errorf("Failure applying security groups to ELB: %s", err)
   595  		}
   596  
   597  		d.SetPartial("security_groups")
   598  	}
   599  
   600  	if d.HasChange("availability_zones") {
   601  		o, n := d.GetChange("availability_zones")
   602  		os := o.(*schema.Set)
   603  		ns := n.(*schema.Set)
   604  
   605  		removed := expandStringList(os.Difference(ns).List())
   606  		added := expandStringList(ns.Difference(os).List())
   607  
   608  		if len(added) > 0 {
   609  			enableOpts := &elb.EnableAvailabilityZonesForLoadBalancerInput{
   610  				LoadBalancerName:  aws.String(d.Id()),
   611  				AvailabilityZones: added,
   612  			}
   613  
   614  			log.Printf("[DEBUG] ELB enable availability zones opts: %s", enableOpts)
   615  			_, err := elbconn.EnableAvailabilityZonesForLoadBalancer(enableOpts)
   616  			if err != nil {
   617  				return fmt.Errorf("Failure enabling ELB availability zones: %s", err)
   618  			}
   619  		}
   620  
   621  		if len(removed) > 0 {
   622  			disableOpts := &elb.DisableAvailabilityZonesForLoadBalancerInput{
   623  				LoadBalancerName:  aws.String(d.Id()),
   624  				AvailabilityZones: removed,
   625  			}
   626  
   627  			log.Printf("[DEBUG] ELB disable availability zones opts: %s", disableOpts)
   628  			_, err := elbconn.DisableAvailabilityZonesForLoadBalancer(disableOpts)
   629  			if err != nil {
   630  				return fmt.Errorf("Failure disabling ELB availability zones: %s", err)
   631  			}
   632  		}
   633  
   634  		d.SetPartial("availability_zones")
   635  	}
   636  
   637  	if d.HasChange("subnets") {
   638  		o, n := d.GetChange("subnets")
   639  		os := o.(*schema.Set)
   640  		ns := n.(*schema.Set)
   641  
   642  		removed := expandStringList(os.Difference(ns).List())
   643  		added := expandStringList(ns.Difference(os).List())
   644  
   645  		if len(added) > 0 {
   646  			attachOpts := &elb.AttachLoadBalancerToSubnetsInput{
   647  				LoadBalancerName: aws.String(d.Id()),
   648  				Subnets:          added,
   649  			}
   650  
   651  			log.Printf("[DEBUG] ELB attach subnets opts: %s", attachOpts)
   652  			_, err := elbconn.AttachLoadBalancerToSubnets(attachOpts)
   653  			if err != nil {
   654  				return fmt.Errorf("Failure adding ELB subnets: %s", err)
   655  			}
   656  		}
   657  
   658  		if len(removed) > 0 {
   659  			detachOpts := &elb.DetachLoadBalancerFromSubnetsInput{
   660  				LoadBalancerName: aws.String(d.Id()),
   661  				Subnets:          removed,
   662  			}
   663  
   664  			log.Printf("[DEBUG] ELB detach subnets opts: %s", detachOpts)
   665  			_, err := elbconn.DetachLoadBalancerFromSubnets(detachOpts)
   666  			if err != nil {
   667  				return fmt.Errorf("Failure removing ELB subnets: %s", err)
   668  			}
   669  		}
   670  
   671  		d.SetPartial("subnets")
   672  	}
   673  
   674  	if err := setTagsELB(elbconn, d); err != nil {
   675  		return err
   676  	}
   677  
   678  	d.SetPartial("tags")
   679  	d.Partial(false)
   680  
   681  	return resourceAwsElbRead(d, meta)
   682  }
   683  
   684  func resourceAwsElbDelete(d *schema.ResourceData, meta interface{}) error {
   685  	elbconn := meta.(*AWSClient).elbconn
   686  
   687  	log.Printf("[INFO] Deleting ELB: %s", d.Id())
   688  
   689  	// Destroy the load balancer
   690  	deleteElbOpts := elb.DeleteLoadBalancerInput{
   691  		LoadBalancerName: aws.String(d.Id()),
   692  	}
   693  	if _, err := elbconn.DeleteLoadBalancer(&deleteElbOpts); err != nil {
   694  		return fmt.Errorf("Error deleting ELB: %s", err)
   695  	}
   696  
   697  	return nil
   698  }
   699  
   700  func resourceAwsElbHealthCheckHash(v interface{}) int {
   701  	var buf bytes.Buffer
   702  	m := v.(map[string]interface{})
   703  	buf.WriteString(fmt.Sprintf("%d-", m["healthy_threshold"].(int)))
   704  	buf.WriteString(fmt.Sprintf("%d-", m["unhealthy_threshold"].(int)))
   705  	buf.WriteString(fmt.Sprintf("%s-", m["target"].(string)))
   706  	buf.WriteString(fmt.Sprintf("%d-", m["interval"].(int)))
   707  	buf.WriteString(fmt.Sprintf("%d-", m["timeout"].(int)))
   708  
   709  	return hashcode.String(buf.String())
   710  }
   711  
   712  func resourceAwsElbAccessLogsHash(v interface{}) int {
   713  	var buf bytes.Buffer
   714  	m := v.(map[string]interface{})
   715  	buf.WriteString(fmt.Sprintf("%d-", m["interval"].(int)))
   716  	buf.WriteString(fmt.Sprintf("%s-",
   717  		strings.ToLower(m["bucket"].(string))))
   718  	if v, ok := m["bucket_prefix"]; ok {
   719  		buf.WriteString(fmt.Sprintf("%s-", strings.ToLower(v.(string))))
   720  	}
   721  
   722  	return hashcode.String(buf.String())
   723  }
   724  
   725  func resourceAwsElbListenerHash(v interface{}) int {
   726  	var buf bytes.Buffer
   727  	m := v.(map[string]interface{})
   728  	buf.WriteString(fmt.Sprintf("%d-", m["instance_port"].(int)))
   729  	buf.WriteString(fmt.Sprintf("%s-",
   730  		strings.ToLower(m["instance_protocol"].(string))))
   731  	buf.WriteString(fmt.Sprintf("%d-", m["lb_port"].(int)))
   732  	buf.WriteString(fmt.Sprintf("%s-",
   733  		strings.ToLower(m["lb_protocol"].(string))))
   734  
   735  	if v, ok := m["ssl_certificate_id"]; ok {
   736  		buf.WriteString(fmt.Sprintf("%s-", v.(string)))
   737  	}
   738  
   739  	return hashcode.String(buf.String())
   740  }
   741  
   742  func isLoadBalancerNotFound(err error) bool {
   743  	elberr, ok := err.(awserr.Error)
   744  	return ok && elberr.Code() == "LoadBalancerNotFound"
   745  }
   746  
   747  func sourceSGIdByName(meta interface{}, sg, vpcId string) (string, error) {
   748  	conn := meta.(*AWSClient).ec2conn
   749  	var filters []*ec2.Filter
   750  	var sgFilterName, sgFilterVPCID *ec2.Filter
   751  	sgFilterName = &ec2.Filter{
   752  		Name:   aws.String("group-name"),
   753  		Values: []*string{aws.String(sg)},
   754  	}
   755  
   756  	if vpcId != "" {
   757  		sgFilterVPCID = &ec2.Filter{
   758  			Name:   aws.String("vpc-id"),
   759  			Values: []*string{aws.String(vpcId)},
   760  		}
   761  	}
   762  
   763  	filters = append(filters, sgFilterName)
   764  
   765  	if sgFilterVPCID != nil {
   766  		filters = append(filters, sgFilterVPCID)
   767  	}
   768  
   769  	req := &ec2.DescribeSecurityGroupsInput{
   770  		Filters: filters,
   771  	}
   772  	resp, err := conn.DescribeSecurityGroups(req)
   773  	if err != nil {
   774  		if ec2err, ok := err.(awserr.Error); ok {
   775  			if ec2err.Code() == "InvalidSecurityGroupID.NotFound" ||
   776  				ec2err.Code() == "InvalidGroup.NotFound" {
   777  				resp = nil
   778  				err = nil
   779  			}
   780  		}
   781  
   782  		if err != nil {
   783  			log.Printf("Error on ELB SG look up: %s", err)
   784  			return "", err
   785  		}
   786  	}
   787  
   788  	if resp == nil || len(resp.SecurityGroups) == 0 {
   789  		return "", fmt.Errorf("No security groups found for name %s and vpc id %s", sg, vpcId)
   790  	}
   791  
   792  	group := resp.SecurityGroups[0]
   793  	return *group.GroupId, nil
   794  }