github.com/paulmey/terraform@v0.5.2-0.20150519145237-046e9b4c884d/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/awslabs/aws-sdk-go/aws"
    13  	"github.com/awslabs/aws-sdk-go/service/autoscaling"
    14  	"github.com/awslabs/aws-sdk-go/service/elb"
    15  )
    16  
    17  func resourceAwsAutoscalingGroup() *schema.Resource {
    18  	return &schema.Resource{
    19  		Create: resourceAwsAutoscalingGroupCreate,
    20  		Read:   resourceAwsAutoscalingGroupRead,
    21  		Update: resourceAwsAutoscalingGroupUpdate,
    22  		Delete: resourceAwsAutoscalingGroupDelete,
    23  
    24  		Schema: map[string]*schema.Schema{
    25  			"name": &schema.Schema{
    26  				Type:     schema.TypeString,
    27  				Required: true,
    28  				ForceNew: true,
    29  			},
    30  
    31  			"launch_configuration": &schema.Schema{
    32  				Type:     schema.TypeString,
    33  				Required: true,
    34  			},
    35  
    36  			"desired_capacity": &schema.Schema{
    37  				Type:     schema.TypeInt,
    38  				Optional: true,
    39  				Computed: true,
    40  			},
    41  
    42  			"min_elb_capacity": &schema.Schema{
    43  				Type:     schema.TypeInt,
    44  				Optional: true,
    45  			},
    46  
    47  			"min_size": &schema.Schema{
    48  				Type:     schema.TypeInt,
    49  				Required: true,
    50  			},
    51  
    52  			"max_size": &schema.Schema{
    53  				Type:     schema.TypeInt,
    54  				Required: true,
    55  			},
    56  
    57  			"default_cooldown": &schema.Schema{
    58  				Type:     schema.TypeInt,
    59  				Optional: true,
    60  				Computed: true,
    61  				ForceNew: true,
    62  			},
    63  
    64  			"force_delete": &schema.Schema{
    65  				Type:     schema.TypeBool,
    66  				Optional: true,
    67  				Computed: true,
    68  				ForceNew: true,
    69  			},
    70  
    71  			"health_check_grace_period": &schema.Schema{
    72  				Type:     schema.TypeInt,
    73  				Optional: true,
    74  				Computed: true,
    75  			},
    76  
    77  			"health_check_type": &schema.Schema{
    78  				Type:     schema.TypeString,
    79  				Optional: true,
    80  				Computed: true,
    81  				ForceNew: true,
    82  			},
    83  
    84  			"availability_zones": &schema.Schema{
    85  				Type:     schema.TypeSet,
    86  				Required: true,
    87  				ForceNew: true,
    88  				Elem:     &schema.Schema{Type: schema.TypeString},
    89  				Set:      schema.HashString,
    90  			},
    91  
    92  			"load_balancers": &schema.Schema{
    93  				Type:     schema.TypeSet,
    94  				Optional: true,
    95  				ForceNew: true,
    96  				Elem:     &schema.Schema{Type: schema.TypeString},
    97  				Set:      schema.HashString,
    98  			},
    99  
   100  			"vpc_zone_identifier": &schema.Schema{
   101  				Type:     schema.TypeSet,
   102  				Optional: true,
   103  				Computed: true,
   104  				ForceNew: true,
   105  				Elem:     &schema.Schema{Type: schema.TypeString},
   106  				Set:      schema.HashString,
   107  			},
   108  
   109  			"termination_policies": &schema.Schema{
   110  				Type:     schema.TypeSet,
   111  				Optional: true,
   112  				Computed: true,
   113  				ForceNew: true,
   114  				Elem:     &schema.Schema{Type: schema.TypeString},
   115  				Set:      schema.HashString,
   116  			},
   117  
   118  			"tag": autoscalingTagsSchema(),
   119  		},
   120  	}
   121  }
   122  
   123  func resourceAwsAutoscalingGroupCreate(d *schema.ResourceData, meta interface{}) error {
   124  	conn := meta.(*AWSClient).autoscalingconn
   125  
   126  	var autoScalingGroupOpts autoscaling.CreateAutoScalingGroupInput
   127  	autoScalingGroupOpts.AutoScalingGroupName = aws.String(d.Get("name").(string))
   128  	autoScalingGroupOpts.LaunchConfigurationName = aws.String(d.Get("launch_configuration").(string))
   129  	autoScalingGroupOpts.MinSize = aws.Long(int64(d.Get("min_size").(int)))
   130  	autoScalingGroupOpts.MaxSize = aws.Long(int64(d.Get("max_size").(int)))
   131  	autoScalingGroupOpts.AvailabilityZones = expandStringList(
   132  		d.Get("availability_zones").(*schema.Set).List())
   133  
   134  	if v, ok := d.GetOk("tag"); ok {
   135  		autoScalingGroupOpts.Tags = autoscalingTagsFromMap(
   136  			setToMapByKey(v.(*schema.Set), "key"), d.Get("name").(string))
   137  	}
   138  
   139  	if v, ok := d.GetOk("default_cooldown"); ok {
   140  		autoScalingGroupOpts.DefaultCooldown = aws.Long(int64(v.(int)))
   141  	}
   142  
   143  	if v, ok := d.GetOk("health_check_type"); ok && v.(string) != "" {
   144  		autoScalingGroupOpts.HealthCheckType = aws.String(v.(string))
   145  	}
   146  
   147  	if v, ok := d.GetOk("desired_capacity"); ok {
   148  		autoScalingGroupOpts.DesiredCapacity = aws.Long(int64(v.(int)))
   149  	}
   150  
   151  	if v, ok := d.GetOk("health_check_grace_period"); ok {
   152  		autoScalingGroupOpts.HealthCheckGracePeriod = aws.Long(int64(v.(int)))
   153  	}
   154  
   155  	if v, ok := d.GetOk("load_balancers"); ok && v.(*schema.Set).Len() > 0 {
   156  		autoScalingGroupOpts.LoadBalancerNames = expandStringList(
   157  			v.(*schema.Set).List())
   158  	}
   159  
   160  	if v, ok := d.GetOk("vpc_zone_identifier"); ok && v.(*schema.Set).Len() > 0 {
   161  		exp := expandStringList(v.(*schema.Set).List())
   162  		strs := make([]string, len(exp))
   163  		for _, s := range exp {
   164  			strs = append(strs, *s)
   165  		}
   166  		autoScalingGroupOpts.VPCZoneIdentifier = aws.String(strings.Join(strs, ","))
   167  	}
   168  
   169  	if v, ok := d.GetOk("termination_policies"); ok && v.(*schema.Set).Len() > 0 {
   170  		autoScalingGroupOpts.TerminationPolicies = expandStringList(
   171  			v.(*schema.Set).List())
   172  	}
   173  
   174  	log.Printf("[DEBUG] AutoScaling Group create configuration: %#v", autoScalingGroupOpts)
   175  	_, err := conn.CreateAutoScalingGroup(&autoScalingGroupOpts)
   176  	if err != nil {
   177  		return fmt.Errorf("Error creating Autoscaling Group: %s", err)
   178  	}
   179  
   180  	d.SetId(d.Get("name").(string))
   181  	log.Printf("[INFO] AutoScaling Group ID: %s", d.Id())
   182  
   183  	if err := waitForASGCapacity(d, meta); err != nil {
   184  		return err
   185  	}
   186  
   187  	return resourceAwsAutoscalingGroupRead(d, meta)
   188  }
   189  
   190  func resourceAwsAutoscalingGroupRead(d *schema.ResourceData, meta interface{}) error {
   191  	g, err := getAwsAutoscalingGroup(d, meta)
   192  	if err != nil {
   193  		return err
   194  	}
   195  	if g == nil {
   196  		return nil
   197  	}
   198  
   199  	d.Set("availability_zones", g.AvailabilityZones)
   200  	d.Set("default_cooldown", g.DefaultCooldown)
   201  	d.Set("desired_capacity", g.DesiredCapacity)
   202  	d.Set("health_check_grace_period", g.HealthCheckGracePeriod)
   203  	d.Set("health_check_type", g.HealthCheckType)
   204  	d.Set("launch_configuration", g.LaunchConfigurationName)
   205  	d.Set("load_balancers", g.LoadBalancerNames)
   206  	d.Set("min_size", g.MinSize)
   207  	d.Set("max_size", g.MaxSize)
   208  	d.Set("name", g.AutoScalingGroupName)
   209  	d.Set("tag", g.Tags)
   210  	d.Set("vpc_zone_identifier", strings.Split(*g.VPCZoneIdentifier, ","))
   211  	d.Set("termination_policies", g.TerminationPolicies)
   212  
   213  	return nil
   214  }
   215  
   216  func resourceAwsAutoscalingGroupUpdate(d *schema.ResourceData, meta interface{}) error {
   217  	conn := meta.(*AWSClient).autoscalingconn
   218  
   219  	opts := autoscaling.UpdateAutoScalingGroupInput{
   220  		AutoScalingGroupName: aws.String(d.Id()),
   221  	}
   222  
   223  	if d.HasChange("desired_capacity") {
   224  		opts.DesiredCapacity = aws.Long(int64(d.Get("desired_capacity").(int)))
   225  	}
   226  
   227  	if d.HasChange("launch_configuration") {
   228  		opts.LaunchConfigurationName = aws.String(d.Get("launch_configuration").(string))
   229  	}
   230  
   231  	if d.HasChange("min_size") {
   232  		opts.MinSize = aws.Long(int64(d.Get("min_size").(int)))
   233  	}
   234  
   235  	if d.HasChange("max_size") {
   236  		opts.MaxSize = aws.Long(int64(d.Get("max_size").(int)))
   237  	}
   238  
   239  	if d.HasChange("health_check_grace_period") {
   240  		opts.HealthCheckGracePeriod = aws.Long(int64(d.Get("health_check_grace_period").(int)))
   241  	}
   242  
   243  	if err := setAutoscalingTags(conn, d); err != nil {
   244  		return err
   245  	} else {
   246  		d.SetPartial("tag")
   247  	}
   248  
   249  	log.Printf("[DEBUG] AutoScaling Group update configuration: %#v", opts)
   250  	_, err := conn.UpdateAutoScalingGroup(&opts)
   251  	if err != nil {
   252  		d.Partial(true)
   253  		return fmt.Errorf("Error updating Autoscaling group: %s", err)
   254  	}
   255  
   256  	return resourceAwsAutoscalingGroupRead(d, meta)
   257  }
   258  
   259  func resourceAwsAutoscalingGroupDelete(d *schema.ResourceData, meta interface{}) error {
   260  	conn := meta.(*AWSClient).autoscalingconn
   261  
   262  	// Read the autoscaling group first. If it doesn't exist, we're done.
   263  	// We need the group in order to check if there are instances attached.
   264  	// If so, we need to remove those first.
   265  	g, err := getAwsAutoscalingGroup(d, meta)
   266  	if err != nil {
   267  		return err
   268  	}
   269  	if g == nil {
   270  		return nil
   271  	}
   272  	if len(g.Instances) > 0 || *g.DesiredCapacity > 0 {
   273  		if err := resourceAwsAutoscalingGroupDrain(d, meta); err != nil {
   274  			return err
   275  		}
   276  	}
   277  
   278  	log.Printf("[DEBUG] AutoScaling Group destroy: %v", d.Id())
   279  	deleteopts := autoscaling.DeleteAutoScalingGroupInput{AutoScalingGroupName: aws.String(d.Id())}
   280  
   281  	// You can force an autoscaling group to delete
   282  	// even if it's in the process of scaling a resource.
   283  	// Normally, you would set the min-size and max-size to 0,0
   284  	// and then delete the group. This bypasses that and leaves
   285  	// resources potentially dangling.
   286  	if d.Get("force_delete").(bool) {
   287  		deleteopts.ForceDelete = aws.Boolean(true)
   288  	}
   289  
   290  	// We retry the delete operation to handle InUse/InProgress errors coming
   291  	// from scaling operations. We should be able to sneak in a delete in between
   292  	// scaling operations within 5m.
   293  	err = resource.Retry(5*time.Minute, func() error {
   294  		if _, err := conn.DeleteAutoScalingGroup(&deleteopts); err != nil {
   295  			if awserr, ok := err.(aws.APIError); ok {
   296  				switch awserr.Code {
   297  				case "InvalidGroup.NotFound":
   298  					// Already gone? Sure!
   299  					return nil
   300  				case "ResourceInUse", "ScalingActivityInProgress":
   301  					// These are retryable
   302  					return awserr
   303  				}
   304  			}
   305  			// Didn't recognize the error, so shouldn't retry.
   306  			return resource.RetryError{Err: err}
   307  		}
   308  		// Successful delete
   309  		return nil
   310  	})
   311  	if err != nil {
   312  		return err
   313  	}
   314  
   315  	return resource.Retry(5*time.Minute, func() error {
   316  		if g, _ = getAwsAutoscalingGroup(d, meta); g != nil {
   317  			return fmt.Errorf("Auto Scaling Group still exists")
   318  		}
   319  		return nil
   320  	})
   321  }
   322  
   323  func getAwsAutoscalingGroup(
   324  	d *schema.ResourceData,
   325  	meta interface{}) (*autoscaling.AutoScalingGroup, error) {
   326  	conn := meta.(*AWSClient).autoscalingconn
   327  
   328  	describeOpts := autoscaling.DescribeAutoScalingGroupsInput{
   329  		AutoScalingGroupNames: []*string{aws.String(d.Id())},
   330  	}
   331  
   332  	log.Printf("[DEBUG] AutoScaling Group describe configuration: %#v", describeOpts)
   333  	describeGroups, err := conn.DescribeAutoScalingGroups(&describeOpts)
   334  	if err != nil {
   335  		autoscalingerr, ok := err.(aws.APIError)
   336  		if ok && autoscalingerr.Code == "InvalidGroup.NotFound" {
   337  			d.SetId("")
   338  			return nil, nil
   339  		}
   340  
   341  		return nil, fmt.Errorf("Error retrieving AutoScaling groups: %s", err)
   342  	}
   343  
   344  	// Search for the autoscaling group
   345  	for idx, asc := range describeGroups.AutoScalingGroups {
   346  		if *asc.AutoScalingGroupName == d.Id() {
   347  			return describeGroups.AutoScalingGroups[idx], nil
   348  		}
   349  	}
   350  
   351  	// ASG not found
   352  	d.SetId("")
   353  	return nil, nil
   354  }
   355  
   356  func resourceAwsAutoscalingGroupDrain(d *schema.ResourceData, meta interface{}) error {
   357  	conn := meta.(*AWSClient).autoscalingconn
   358  
   359  	// First, set the capacity to zero so the group will drain
   360  	log.Printf("[DEBUG] Reducing autoscaling group capacity to zero")
   361  	opts := autoscaling.UpdateAutoScalingGroupInput{
   362  		AutoScalingGroupName: aws.String(d.Id()),
   363  		DesiredCapacity:      aws.Long(0),
   364  		MinSize:              aws.Long(0),
   365  		MaxSize:              aws.Long(0),
   366  	}
   367  	if _, err := conn.UpdateAutoScalingGroup(&opts); err != nil {
   368  		return fmt.Errorf("Error setting capacity to zero to drain: %s", err)
   369  	}
   370  
   371  	// Next, wait for the autoscale group to drain
   372  	log.Printf("[DEBUG] Waiting for group to have zero instances")
   373  	return resource.Retry(10*time.Minute, func() error {
   374  		g, err := getAwsAutoscalingGroup(d, meta)
   375  		if err != nil {
   376  			return resource.RetryError{Err: err}
   377  		}
   378  		if g == nil {
   379  			return nil
   380  		}
   381  
   382  		if len(g.Instances) == 0 {
   383  			return nil
   384  		}
   385  
   386  		return fmt.Errorf("group still has %d instances", len(g.Instances))
   387  	})
   388  }
   389  
   390  var waitForASGCapacityTimeout = 10 * time.Minute
   391  
   392  // Waits for a minimum number of healthy instances to show up as healthy in the
   393  // ASG before continuing. Waits up to `waitForASGCapacityTimeout` for
   394  // "desired_capacity", or "min_size" if desired capacity is not specified.
   395  //
   396  // If "min_elb_capacity" is specified, will also wait for that number of
   397  // instances to show up InService in all attached ELBs. See "Waiting for
   398  // Capacity" in docs for more discussion of the feature.
   399  func waitForASGCapacity(d *schema.ResourceData, meta interface{}) error {
   400  	wantASG := d.Get("min_size").(int)
   401  	if v := d.Get("desired_capacity").(int); v > 0 {
   402  		wantASG = v
   403  	}
   404  	wantELB := d.Get("min_elb_capacity").(int)
   405  
   406  	log.Printf("[DEBUG] Wanting for capacity: %d ASG, %d ELB", wantASG, wantELB)
   407  
   408  	return resource.Retry(waitForASGCapacityTimeout, func() error {
   409  		g, err := getAwsAutoscalingGroup(d, meta)
   410  		if err != nil {
   411  			return resource.RetryError{Err: err}
   412  		}
   413  		if g == nil {
   414  			return nil
   415  		}
   416  		lbis, err := getLBInstanceStates(g, meta)
   417  		if err != nil {
   418  			return resource.RetryError{Err: err}
   419  		}
   420  
   421  		haveASG := 0
   422  		haveELB := 0
   423  
   424  		for _, i := range g.Instances {
   425  			if i.HealthStatus == nil || i.InstanceID == nil || i.LifecycleState == nil {
   426  				continue
   427  			}
   428  
   429  			if !strings.EqualFold(*i.HealthStatus, "Healthy") {
   430  				continue
   431  			}
   432  
   433  			if !strings.EqualFold(*i.LifecycleState, "InService") {
   434  				continue
   435  			}
   436  
   437  			haveASG++
   438  
   439  			if wantELB > 0 {
   440  				inAllLbs := true
   441  				for _, states := range lbis {
   442  					state, ok := states[*i.InstanceID]
   443  					if !ok || !strings.EqualFold(state, "InService") {
   444  						inAllLbs = false
   445  					}
   446  				}
   447  				if inAllLbs {
   448  					haveELB++
   449  				}
   450  			}
   451  		}
   452  
   453  		log.Printf("[DEBUG] %q Capacity: %d/%d ASG, %d/%d ELB",
   454  			d.Id(), haveASG, wantASG, haveELB, wantELB)
   455  
   456  		if haveASG >= wantASG && haveELB >= wantELB {
   457  			return nil
   458  		}
   459  
   460  		return fmt.Errorf("Still need to wait for more healthy instances.")
   461  	})
   462  }
   463  
   464  // Returns a mapping of the instance states of all the ELBs attached to the
   465  // provided ASG.
   466  //
   467  // Nested like: lbName -> instanceId -> instanceState
   468  func getLBInstanceStates(g *autoscaling.AutoScalingGroup, meta interface{}) (map[string]map[string]string, error) {
   469  	lbInstanceStates := make(map[string]map[string]string)
   470  	elbconn := meta.(*AWSClient).elbconn
   471  
   472  	for _, lbName := range g.LoadBalancerNames {
   473  		lbInstanceStates[*lbName] = make(map[string]string)
   474  		opts := &elb.DescribeInstanceHealthInput{LoadBalancerName: lbName}
   475  		r, err := elbconn.DescribeInstanceHealth(opts)
   476  		if err != nil {
   477  			return nil, err
   478  		}
   479  		for _, is := range r.InstanceStates {
   480  			if is.InstanceID == nil || is.State == nil {
   481  				continue
   482  			}
   483  			lbInstanceStates[*lbName][*is.InstanceID] = *is.State
   484  		}
   485  	}
   486  
   487  	return lbInstanceStates, nil
   488  }