diff --git a/builtin/providers/aws/resource_aws_autoscaling_group.go b/builtin/providers/aws/resource_aws_autoscaling_group.go index 17110e70c67c..bbefbc36ef42 100644 --- a/builtin/providers/aws/resource_aws_autoscaling_group.go +++ b/builtin/providers/aws/resource_aws_autoscaling_group.go @@ -154,6 +154,11 @@ func resourceAwsAutoscalingGroup() *schema.Resource { Set: schema.HashString, }, + "delete_delay": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + }, + "metrics_granularity": &schema.Schema{ Type: schema.TypeString, Optional: true, @@ -624,6 +629,20 @@ func getAwsAutoscalingGroup( return nil, nil } +func resourceAwsAutoscalingScaleDownToCount(d *schema.ResourceData, count int64, conn *autoscaling.AutoScaling) error { + log.Printf("[DEBUG] Reducing autoscaling group capacity to %d", count) + opts := autoscaling.UpdateAutoScalingGroupInput{ + AutoScalingGroupName: aws.String(d.Id()), + MinSize: aws.Int64(0), + DesiredCapacity: aws.Int64(count), + MaxSize: aws.Int64(count), + } + if _, err := conn.UpdateAutoScalingGroup(&opts); err != nil { + return fmt.Errorf("Error setting capacity to %d to drain: %s", count, err) + } + return nil +} + func resourceAwsAutoscalingGroupDrain(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).autoscalingconn @@ -632,20 +651,36 @@ func resourceAwsAutoscalingGroupDrain(d *schema.ResourceData, meta interface{}) return nil } - // First, set the capacity to zero so the group will drain - log.Printf("[DEBUG] Reducing autoscaling group capacity to zero") - opts := autoscaling.UpdateAutoScalingGroupInput{ - AutoScalingGroupName: aws.String(d.Id()), - DesiredCapacity: aws.Int64(0), - MinSize: aws.Int64(0), - MaxSize: aws.Int64(0), - } - if _, err := conn.UpdateAutoScalingGroup(&opts); err != nil { - return fmt.Errorf("Error setting capacity to zero to drain: %s", err) + if delay, ok := d.GetOk("delete_delay"); ok { + g, err := getAwsAutoscalingGroup(d.Id(), conn) + if err != nil { + return err + } + delayT := time.Duration(delay.(int)) * time.Second + t := time.Now() + count := *g.DesiredCapacity + for count > 0 { + count-- + if err := resourceAwsAutoscalingScaleDownToCount(d, count, conn); err != nil { + return err + } + if count != 0 { + now := time.Now() + sleepTime := delayT - now.Sub(t) + t = now + if sleepTime > 0 { + time.Sleep(sleepTime) + } + } + } + } else { + if err := resourceAwsAutoscalingScaleDownToCount(d, 0, conn); err != nil { + return err + } } // Next, wait for the autoscale group to drain - log.Printf("[DEBUG] Waiting for group to have zero instances") + log.Printf("[DEBUG] Waiting for group to have 0 instances") return resource.Retry(10*time.Minute, func() *resource.RetryError { g, err := getAwsAutoscalingGroup(d.Id(), conn) if err != nil {