github.com/gabrielperezs/terraform@v0.7.0-rc2.0.20160715084931-f7da2612946f/builtin/providers/aws/resource_aws_autoscaling_group.go (about)

     1  package aws
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"strings"
     7  	"time"
     8  
     9  	"github.com/hashicorp/terraform/helper/resource"
    10  	"github.com/hashicorp/terraform/helper/schema"
    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/autoscaling"
    15  	"github.com/aws/aws-sdk-go/service/elb"
    16  )
    17  
    18  func resourceAwsAutoscalingGroup() *schema.Resource {
    19  	return &schema.Resource{
    20  		Create: resourceAwsAutoscalingGroupCreate,
    21  		Read:   resourceAwsAutoscalingGroupRead,
    22  		Update: resourceAwsAutoscalingGroupUpdate,
    23  		Delete: resourceAwsAutoscalingGroupDelete,
    24  		Importer: &schema.ResourceImporter{
    25  			State: schema.ImportStatePassthrough,
    26  		},
    27  
    28  		Schema: map[string]*schema.Schema{
    29  			"name": &schema.Schema{
    30  				Type:     schema.TypeString,
    31  				Optional: true,
    32  				Computed: true,
    33  				ForceNew: true,
    34  				ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
    35  					// https://github.com/boto/botocore/blob/9f322b1/botocore/data/autoscaling/2011-01-01/service-2.json#L1862-L1873
    36  					value := v.(string)
    37  					if len(value) > 255 {
    38  						errors = append(errors, fmt.Errorf(
    39  							"%q cannot be longer than 255 characters", k))
    40  					}
    41  					return
    42  				},
    43  			},
    44  
    45  			"launch_configuration": &schema.Schema{
    46  				Type:     schema.TypeString,
    47  				Required: true,
    48  			},
    49  
    50  			"desired_capacity": &schema.Schema{
    51  				Type:     schema.TypeInt,
    52  				Optional: true,
    53  				Computed: true,
    54  			},
    55  
    56  			"min_elb_capacity": &schema.Schema{
    57  				Type:     schema.TypeInt,
    58  				Optional: true,
    59  			},
    60  
    61  			"min_size": &schema.Schema{
    62  				Type:     schema.TypeInt,
    63  				Required: true,
    64  			},
    65  
    66  			"max_size": &schema.Schema{
    67  				Type:     schema.TypeInt,
    68  				Required: true,
    69  			},
    70  
    71  			"default_cooldown": &schema.Schema{
    72  				Type:     schema.TypeInt,
    73  				Optional: true,
    74  				Computed: true,
    75  			},
    76  
    77  			"force_delete": &schema.Schema{
    78  				Type:     schema.TypeBool,
    79  				Optional: true,
    80  				Default:  false,
    81  			},
    82  
    83  			"health_check_grace_period": &schema.Schema{
    84  				Type:     schema.TypeInt,
    85  				Optional: true,
    86  				Default:  300,
    87  			},
    88  
    89  			"health_check_type": &schema.Schema{
    90  				Type:     schema.TypeString,
    91  				Optional: true,
    92  				Computed: true,
    93  			},
    94  
    95  			"availability_zones": &schema.Schema{
    96  				Type:     schema.TypeSet,
    97  				Optional: true,
    98  				Computed: true,
    99  				Elem:     &schema.Schema{Type: schema.TypeString},
   100  				Set:      schema.HashString,
   101  			},
   102  
   103  			"placement_group": &schema.Schema{
   104  				Type:     schema.TypeString,
   105  				Optional: true,
   106  			},
   107  
   108  			"load_balancers": &schema.Schema{
   109  				Type:     schema.TypeSet,
   110  				Optional: true,
   111  				Elem:     &schema.Schema{Type: schema.TypeString},
   112  				Set:      schema.HashString,
   113  			},
   114  
   115  			"vpc_zone_identifier": &schema.Schema{
   116  				Type:     schema.TypeSet,
   117  				Optional: true,
   118  				Computed: true,
   119  				Elem:     &schema.Schema{Type: schema.TypeString},
   120  				Set:      schema.HashString,
   121  			},
   122  
   123  			"termination_policies": &schema.Schema{
   124  				Type:     schema.TypeList,
   125  				Optional: true,
   126  				Elem:     &schema.Schema{Type: schema.TypeString},
   127  			},
   128  
   129  			"wait_for_capacity_timeout": &schema.Schema{
   130  				Type:     schema.TypeString,
   131  				Optional: true,
   132  				Default:  "10m",
   133  				ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
   134  					value := v.(string)
   135  					duration, err := time.ParseDuration(value)
   136  					if err != nil {
   137  						errors = append(errors, fmt.Errorf(
   138  							"%q cannot be parsed as a duration: %s", k, err))
   139  					}
   140  					if duration < 0 {
   141  						errors = append(errors, fmt.Errorf(
   142  							"%q must be greater than zero", k))
   143  					}
   144  					return
   145  				},
   146  			},
   147  
   148  			"wait_for_elb_capacity": &schema.Schema{
   149  				Type:     schema.TypeInt,
   150  				Optional: true,
   151  			},
   152  
   153  			"enabled_metrics": &schema.Schema{
   154  				Type:     schema.TypeSet,
   155  				Optional: true,
   156  				Elem:     &schema.Schema{Type: schema.TypeString},
   157  				Set:      schema.HashString,
   158  			},
   159  
   160  			"metrics_granularity": &schema.Schema{
   161  				Type:     schema.TypeString,
   162  				Optional: true,
   163  				Default:  "1Minute",
   164  			},
   165  
   166  			"protect_from_scale_in": &schema.Schema{
   167  				Type:     schema.TypeBool,
   168  				Optional: true,
   169  				Default:  false,
   170  			},
   171  
   172  			"tag": autoscalingTagsSchema(),
   173  		},
   174  	}
   175  }
   176  
   177  func resourceAwsAutoscalingGroupCreate(d *schema.ResourceData, meta interface{}) error {
   178  	conn := meta.(*AWSClient).autoscalingconn
   179  
   180  	var autoScalingGroupOpts autoscaling.CreateAutoScalingGroupInput
   181  
   182  	var asgName string
   183  	if v, ok := d.GetOk("name"); ok {
   184  		asgName = v.(string)
   185  	} else {
   186  		asgName = resource.PrefixedUniqueId("tf-asg-")
   187  		d.Set("name", asgName)
   188  	}
   189  
   190  	autoScalingGroupOpts.AutoScalingGroupName = aws.String(asgName)
   191  	autoScalingGroupOpts.LaunchConfigurationName = aws.String(d.Get("launch_configuration").(string))
   192  	autoScalingGroupOpts.MinSize = aws.Int64(int64(d.Get("min_size").(int)))
   193  	autoScalingGroupOpts.MaxSize = aws.Int64(int64(d.Get("max_size").(int)))
   194  	autoScalingGroupOpts.NewInstancesProtectedFromScaleIn = aws.Bool(d.Get("protect_from_scale_in").(bool))
   195  
   196  	// Availability Zones are optional if VPC Zone Identifer(s) are specified
   197  	if v, ok := d.GetOk("availability_zones"); ok && v.(*schema.Set).Len() > 0 {
   198  		autoScalingGroupOpts.AvailabilityZones = expandStringList(v.(*schema.Set).List())
   199  	}
   200  
   201  	if v, ok := d.GetOk("tag"); ok {
   202  		autoScalingGroupOpts.Tags = autoscalingTagsFromMap(
   203  			setToMapByKey(v.(*schema.Set), "key"), d.Get("name").(string))
   204  	}
   205  
   206  	if v, ok := d.GetOk("default_cooldown"); ok {
   207  		autoScalingGroupOpts.DefaultCooldown = aws.Int64(int64(v.(int)))
   208  	}
   209  
   210  	if v, ok := d.GetOk("health_check_type"); ok && v.(string) != "" {
   211  		autoScalingGroupOpts.HealthCheckType = aws.String(v.(string))
   212  	}
   213  
   214  	if v, ok := d.GetOk("desired_capacity"); ok {
   215  		autoScalingGroupOpts.DesiredCapacity = aws.Int64(int64(v.(int)))
   216  	}
   217  
   218  	if v, ok := d.GetOk("health_check_grace_period"); ok {
   219  		autoScalingGroupOpts.HealthCheckGracePeriod = aws.Int64(int64(v.(int)))
   220  	}
   221  
   222  	if v, ok := d.GetOk("placement_group"); ok {
   223  		autoScalingGroupOpts.PlacementGroup = aws.String(v.(string))
   224  	}
   225  
   226  	if v, ok := d.GetOk("load_balancers"); ok && v.(*schema.Set).Len() > 0 {
   227  		autoScalingGroupOpts.LoadBalancerNames = expandStringList(
   228  			v.(*schema.Set).List())
   229  	}
   230  
   231  	if v, ok := d.GetOk("vpc_zone_identifier"); ok && v.(*schema.Set).Len() > 0 {
   232  		autoScalingGroupOpts.VPCZoneIdentifier = expandVpcZoneIdentifiers(v.(*schema.Set).List())
   233  	}
   234  
   235  	if v, ok := d.GetOk("termination_policies"); ok && len(v.([]interface{})) > 0 {
   236  		autoScalingGroupOpts.TerminationPolicies = expandStringList(v.([]interface{}))
   237  	}
   238  
   239  	log.Printf("[DEBUG] AutoScaling Group create configuration: %#v", autoScalingGroupOpts)
   240  	_, err := conn.CreateAutoScalingGroup(&autoScalingGroupOpts)
   241  	if err != nil {
   242  		return fmt.Errorf("Error creating Autoscaling Group: %s", err)
   243  	}
   244  
   245  	d.SetId(d.Get("name").(string))
   246  	log.Printf("[INFO] AutoScaling Group ID: %s", d.Id())
   247  
   248  	if err := waitForASGCapacity(d, meta, capacitySatifiedCreate); err != nil {
   249  		return err
   250  	}
   251  
   252  	if _, ok := d.GetOk("enabled_metrics"); ok {
   253  		metricsErr := enableASGMetricsCollection(d, conn)
   254  		if metricsErr != nil {
   255  			return metricsErr
   256  		}
   257  	}
   258  
   259  	return resourceAwsAutoscalingGroupRead(d, meta)
   260  }
   261  
   262  func resourceAwsAutoscalingGroupRead(d *schema.ResourceData, meta interface{}) error {
   263  	conn := meta.(*AWSClient).autoscalingconn
   264  
   265  	g, err := getAwsAutoscalingGroup(d.Id(), conn)
   266  	if err != nil {
   267  		return err
   268  	}
   269  	if g == nil {
   270  		log.Printf("[INFO] Autoscaling Group %q not found", d.Id())
   271  		d.SetId("")
   272  		return nil
   273  	}
   274  
   275  	d.Set("availability_zones", flattenStringList(g.AvailabilityZones))
   276  	d.Set("default_cooldown", g.DefaultCooldown)
   277  	d.Set("desired_capacity", g.DesiredCapacity)
   278  	d.Set("health_check_grace_period", g.HealthCheckGracePeriod)
   279  	d.Set("health_check_type", g.HealthCheckType)
   280  	d.Set("launch_configuration", g.LaunchConfigurationName)
   281  	d.Set("load_balancers", flattenStringList(g.LoadBalancerNames))
   282  	d.Set("min_size", g.MinSize)
   283  	d.Set("max_size", g.MaxSize)
   284  	d.Set("placement_group", g.PlacementGroup)
   285  	d.Set("name", g.AutoScalingGroupName)
   286  	d.Set("tag", autoscalingTagDescriptionsToSlice(g.Tags))
   287  	d.Set("vpc_zone_identifier", strings.Split(*g.VPCZoneIdentifier, ","))
   288  	d.Set("protect_from_scale_in", g.NewInstancesProtectedFromScaleIn)
   289  
   290  	// If no termination polices are explicitly configured and the upstream state
   291  	// is only using the "Default" policy, clear the state to make it consistent
   292  	// with the default AWS create API behavior.
   293  	_, ok := d.GetOk("termination_policies")
   294  	if !ok && len(g.TerminationPolicies) == 1 && *g.TerminationPolicies[0] == "Default" {
   295  		d.Set("termination_policies", []interface{}{})
   296  	} else {
   297  		d.Set("termination_policies", flattenStringList(g.TerminationPolicies))
   298  	}
   299  
   300  	if g.EnabledMetrics != nil {
   301  		if err := d.Set("enabled_metrics", flattenAsgEnabledMetrics(g.EnabledMetrics)); err != nil {
   302  			log.Printf("[WARN] Error setting metrics for (%s): %s", d.Id(), err)
   303  		}
   304  		d.Set("metrics_granularity", g.EnabledMetrics[0].Granularity)
   305  	}
   306  
   307  	return nil
   308  }
   309  
   310  func resourceAwsAutoscalingGroupUpdate(d *schema.ResourceData, meta interface{}) error {
   311  	conn := meta.(*AWSClient).autoscalingconn
   312  	shouldWaitForCapacity := false
   313  
   314  	opts := autoscaling.UpdateAutoScalingGroupInput{
   315  		AutoScalingGroupName: aws.String(d.Id()),
   316  	}
   317  
   318  	opts.NewInstancesProtectedFromScaleIn = aws.Bool(d.Get("protect_from_scale_in").(bool))
   319  
   320  	if d.HasChange("default_cooldown") {
   321  		opts.DefaultCooldown = aws.Int64(int64(d.Get("default_cooldown").(int)))
   322  	}
   323  
   324  	if d.HasChange("desired_capacity") {
   325  		opts.DesiredCapacity = aws.Int64(int64(d.Get("desired_capacity").(int)))
   326  		shouldWaitForCapacity = true
   327  	}
   328  
   329  	if d.HasChange("launch_configuration") {
   330  		opts.LaunchConfigurationName = aws.String(d.Get("launch_configuration").(string))
   331  	}
   332  
   333  	if d.HasChange("min_size") {
   334  		opts.MinSize = aws.Int64(int64(d.Get("min_size").(int)))
   335  		shouldWaitForCapacity = true
   336  	}
   337  
   338  	if d.HasChange("max_size") {
   339  		opts.MaxSize = aws.Int64(int64(d.Get("max_size").(int)))
   340  	}
   341  
   342  	if d.HasChange("health_check_grace_period") {
   343  		opts.HealthCheckGracePeriod = aws.Int64(int64(d.Get("health_check_grace_period").(int)))
   344  	}
   345  
   346  	if d.HasChange("health_check_type") {
   347  		opts.HealthCheckGracePeriod = aws.Int64(int64(d.Get("health_check_grace_period").(int)))
   348  		opts.HealthCheckType = aws.String(d.Get("health_check_type").(string))
   349  	}
   350  
   351  	if d.HasChange("vpc_zone_identifier") {
   352  		opts.VPCZoneIdentifier = expandVpcZoneIdentifiers(d.Get("vpc_zone_identifier").(*schema.Set).List())
   353  	}
   354  
   355  	if d.HasChange("availability_zones") {
   356  		if v, ok := d.GetOk("availability_zones"); ok && v.(*schema.Set).Len() > 0 {
   357  			opts.AvailabilityZones = expandStringList(v.(*schema.Set).List())
   358  		}
   359  	}
   360  
   361  	if d.HasChange("placement_group") {
   362  		opts.PlacementGroup = aws.String(d.Get("placement_group").(string))
   363  	}
   364  
   365  	if d.HasChange("termination_policies") {
   366  		// If the termination policy is set to null, we need to explicitly set
   367  		// it back to "Default", or the API won't reset it for us.
   368  		if v, ok := d.GetOk("termination_policies"); ok && len(v.([]interface{})) > 0 {
   369  			opts.TerminationPolicies = expandStringList(v.([]interface{}))
   370  		} else {
   371  			log.Printf("[DEBUG] Explictly setting null termination policy to 'Default'")
   372  			opts.TerminationPolicies = aws.StringSlice([]string{"Default"})
   373  		}
   374  	}
   375  
   376  	if err := setAutoscalingTags(conn, d); err != nil {
   377  		return err
   378  	} else {
   379  		d.SetPartial("tag")
   380  	}
   381  
   382  	log.Printf("[DEBUG] AutoScaling Group update configuration: %#v", opts)
   383  	_, err := conn.UpdateAutoScalingGroup(&opts)
   384  	if err != nil {
   385  		d.Partial(true)
   386  		return fmt.Errorf("Error updating Autoscaling group: %s", err)
   387  	}
   388  
   389  	if d.HasChange("load_balancers") {
   390  
   391  		o, n := d.GetChange("load_balancers")
   392  		if o == nil {
   393  			o = new(schema.Set)
   394  		}
   395  		if n == nil {
   396  			n = new(schema.Set)
   397  		}
   398  
   399  		os := o.(*schema.Set)
   400  		ns := n.(*schema.Set)
   401  		remove := expandStringList(os.Difference(ns).List())
   402  		add := expandStringList(ns.Difference(os).List())
   403  
   404  		if len(remove) > 0 {
   405  			_, err := conn.DetachLoadBalancers(&autoscaling.DetachLoadBalancersInput{
   406  				AutoScalingGroupName: aws.String(d.Id()),
   407  				LoadBalancerNames:    remove,
   408  			})
   409  			if err != nil {
   410  				return fmt.Errorf("[WARN] Error updating Load Balancers for AutoScaling Group (%s), error: %s", d.Id(), err)
   411  			}
   412  		}
   413  
   414  		if len(add) > 0 {
   415  			_, err := conn.AttachLoadBalancers(&autoscaling.AttachLoadBalancersInput{
   416  				AutoScalingGroupName: aws.String(d.Id()),
   417  				LoadBalancerNames:    add,
   418  			})
   419  			if err != nil {
   420  				return fmt.Errorf("[WARN] Error updating Load Balancers for AutoScaling Group (%s), error: %s", d.Id(), err)
   421  			}
   422  		}
   423  	}
   424  
   425  	if shouldWaitForCapacity {
   426  		waitForASGCapacity(d, meta, capacitySatifiedUpdate)
   427  	}
   428  
   429  	if d.HasChange("enabled_metrics") {
   430  		updateASGMetricsCollection(d, conn)
   431  	}
   432  
   433  	return resourceAwsAutoscalingGroupRead(d, meta)
   434  }
   435  
   436  func resourceAwsAutoscalingGroupDelete(d *schema.ResourceData, meta interface{}) error {
   437  	conn := meta.(*AWSClient).autoscalingconn
   438  
   439  	// Read the autoscaling group first. If it doesn't exist, we're done.
   440  	// We need the group in order to check if there are instances attached.
   441  	// If so, we need to remove those first.
   442  	g, err := getAwsAutoscalingGroup(d.Id(), conn)
   443  	if err != nil {
   444  		return err
   445  	}
   446  	if g == nil {
   447  		log.Printf("[INFO] Autoscaling Group %q not found", d.Id())
   448  		d.SetId("")
   449  		return nil
   450  	}
   451  	if len(g.Instances) > 0 || *g.DesiredCapacity > 0 {
   452  		if err := resourceAwsAutoscalingGroupDrain(d, meta); err != nil {
   453  			return err
   454  		}
   455  	}
   456  
   457  	log.Printf("[DEBUG] AutoScaling Group destroy: %v", d.Id())
   458  	deleteopts := autoscaling.DeleteAutoScalingGroupInput{
   459  		AutoScalingGroupName: aws.String(d.Id()),
   460  		ForceDelete:          aws.Bool(d.Get("force_delete").(bool)),
   461  	}
   462  
   463  	// We retry the delete operation to handle InUse/InProgress errors coming
   464  	// from scaling operations. We should be able to sneak in a delete in between
   465  	// scaling operations within 5m.
   466  	err = resource.Retry(5*time.Minute, func() *resource.RetryError {
   467  		if _, err := conn.DeleteAutoScalingGroup(&deleteopts); err != nil {
   468  			if awserr, ok := err.(awserr.Error); ok {
   469  				switch awserr.Code() {
   470  				case "InvalidGroup.NotFound":
   471  					// Already gone? Sure!
   472  					return nil
   473  				case "ResourceInUse", "ScalingActivityInProgress":
   474  					// These are retryable
   475  					return resource.RetryableError(awserr)
   476  				}
   477  			}
   478  			// Didn't recognize the error, so shouldn't retry.
   479  			return resource.NonRetryableError(err)
   480  		}
   481  		// Successful delete
   482  		return nil
   483  	})
   484  	if err != nil {
   485  		return err
   486  	}
   487  
   488  	return resource.Retry(5*time.Minute, func() *resource.RetryError {
   489  		if g, _ = getAwsAutoscalingGroup(d.Id(), conn); g != nil {
   490  			return resource.RetryableError(
   491  				fmt.Errorf("Auto Scaling Group still exists"))
   492  		}
   493  		return nil
   494  	})
   495  }
   496  
   497  func getAwsAutoscalingGroup(
   498  	asgName string,
   499  	conn *autoscaling.AutoScaling) (*autoscaling.Group, error) {
   500  
   501  	describeOpts := autoscaling.DescribeAutoScalingGroupsInput{
   502  		AutoScalingGroupNames: []*string{aws.String(asgName)},
   503  	}
   504  
   505  	log.Printf("[DEBUG] AutoScaling Group describe configuration: %#v", describeOpts)
   506  	describeGroups, err := conn.DescribeAutoScalingGroups(&describeOpts)
   507  	if err != nil {
   508  		autoscalingerr, ok := err.(awserr.Error)
   509  		if ok && autoscalingerr.Code() == "InvalidGroup.NotFound" {
   510  			return nil, nil
   511  		}
   512  
   513  		return nil, fmt.Errorf("Error retrieving AutoScaling groups: %s", err)
   514  	}
   515  
   516  	// Search for the autoscaling group
   517  	for idx, asc := range describeGroups.AutoScalingGroups {
   518  		if *asc.AutoScalingGroupName == asgName {
   519  			return describeGroups.AutoScalingGroups[idx], nil
   520  		}
   521  	}
   522  
   523  	return nil, nil
   524  }
   525  
   526  func resourceAwsAutoscalingGroupDrain(d *schema.ResourceData, meta interface{}) error {
   527  	conn := meta.(*AWSClient).autoscalingconn
   528  
   529  	if d.Get("force_delete").(bool) {
   530  		log.Printf("[DEBUG] Skipping ASG drain, force_delete was set.")
   531  		return nil
   532  	}
   533  
   534  	// First, set the capacity to zero so the group will drain
   535  	log.Printf("[DEBUG] Reducing autoscaling group capacity to zero")
   536  	opts := autoscaling.UpdateAutoScalingGroupInput{
   537  		AutoScalingGroupName: aws.String(d.Id()),
   538  		DesiredCapacity:      aws.Int64(0),
   539  		MinSize:              aws.Int64(0),
   540  		MaxSize:              aws.Int64(0),
   541  	}
   542  	if _, err := conn.UpdateAutoScalingGroup(&opts); err != nil {
   543  		return fmt.Errorf("Error setting capacity to zero to drain: %s", err)
   544  	}
   545  
   546  	// Next, wait for the autoscale group to drain
   547  	log.Printf("[DEBUG] Waiting for group to have zero instances")
   548  	return resource.Retry(10*time.Minute, func() *resource.RetryError {
   549  		g, err := getAwsAutoscalingGroup(d.Id(), conn)
   550  		if err != nil {
   551  			return resource.NonRetryableError(err)
   552  		}
   553  		if g == nil {
   554  			log.Printf("[INFO] Autoscaling Group %q not found", d.Id())
   555  			d.SetId("")
   556  			return nil
   557  		}
   558  
   559  		if len(g.Instances) == 0 {
   560  			return nil
   561  		}
   562  
   563  		return resource.RetryableError(
   564  			fmt.Errorf("group still has %d instances", len(g.Instances)))
   565  	})
   566  }
   567  
   568  func enableASGMetricsCollection(d *schema.ResourceData, conn *autoscaling.AutoScaling) error {
   569  	props := &autoscaling.EnableMetricsCollectionInput{
   570  		AutoScalingGroupName: aws.String(d.Id()),
   571  		Granularity:          aws.String(d.Get("metrics_granularity").(string)),
   572  		Metrics:              expandStringList(d.Get("enabled_metrics").(*schema.Set).List()),
   573  	}
   574  
   575  	log.Printf("[INFO] Enabling metrics collection for the ASG: %s", d.Id())
   576  	_, metricsErr := conn.EnableMetricsCollection(props)
   577  	if metricsErr != nil {
   578  		return metricsErr
   579  	}
   580  
   581  	return nil
   582  }
   583  
   584  func updateASGMetricsCollection(d *schema.ResourceData, conn *autoscaling.AutoScaling) error {
   585  
   586  	o, n := d.GetChange("enabled_metrics")
   587  	if o == nil {
   588  		o = new(schema.Set)
   589  	}
   590  	if n == nil {
   591  		n = new(schema.Set)
   592  	}
   593  
   594  	os := o.(*schema.Set)
   595  	ns := n.(*schema.Set)
   596  
   597  	disableMetrics := os.Difference(ns)
   598  	if disableMetrics.Len() != 0 {
   599  		props := &autoscaling.DisableMetricsCollectionInput{
   600  			AutoScalingGroupName: aws.String(d.Id()),
   601  			Metrics:              expandStringList(disableMetrics.List()),
   602  		}
   603  
   604  		_, err := conn.DisableMetricsCollection(props)
   605  		if err != nil {
   606  			return fmt.Errorf("Failure to Disable metrics collection types for ASG %s: %s", d.Id(), err)
   607  		}
   608  	}
   609  
   610  	enabledMetrics := ns.Difference(os)
   611  	if enabledMetrics.Len() != 0 {
   612  		props := &autoscaling.EnableMetricsCollectionInput{
   613  			AutoScalingGroupName: aws.String(d.Id()),
   614  			Metrics:              expandStringList(enabledMetrics.List()),
   615  		}
   616  
   617  		_, err := conn.EnableMetricsCollection(props)
   618  		if err != nil {
   619  			return fmt.Errorf("Failure to Enable metrics collection types for ASG %s: %s", d.Id(), err)
   620  		}
   621  	}
   622  
   623  	return nil
   624  }
   625  
   626  // Returns a mapping of the instance states of all the ELBs attached to the
   627  // provided ASG.
   628  //
   629  // Nested like: lbName -> instanceId -> instanceState
   630  func getLBInstanceStates(g *autoscaling.Group, meta interface{}) (map[string]map[string]string, error) {
   631  	lbInstanceStates := make(map[string]map[string]string)
   632  	elbconn := meta.(*AWSClient).elbconn
   633  
   634  	for _, lbName := range g.LoadBalancerNames {
   635  		lbInstanceStates[*lbName] = make(map[string]string)
   636  		opts := &elb.DescribeInstanceHealthInput{LoadBalancerName: lbName}
   637  		r, err := elbconn.DescribeInstanceHealth(opts)
   638  		if err != nil {
   639  			return nil, err
   640  		}
   641  		for _, is := range r.InstanceStates {
   642  			if is.InstanceId == nil || is.State == nil {
   643  				continue
   644  			}
   645  			lbInstanceStates[*lbName][*is.InstanceId] = *is.State
   646  		}
   647  	}
   648  
   649  	return lbInstanceStates, nil
   650  }
   651  
   652  func expandVpcZoneIdentifiers(list []interface{}) *string {
   653  	strs := make([]string, len(list))
   654  	for _, s := range list {
   655  		strs = append(strs, s.(string))
   656  	}
   657  	return aws.String(strings.Join(strs, ","))
   658  }