github.com/recobe182/terraform@v0.8.5-0.20170117231232-49ab22a935b7/builtin/providers/aws/resource_aws_elb.go (about)

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