Skip to content

Commit

Permalink
providers/aws: support slow draining
Browse files Browse the repository at this point in the history
  • Loading branch information
Pierre Carrier authored and glasser committed Apr 19, 2016
1 parent 5d08b4c commit 4df071f
Showing 1 changed file with 46 additions and 11 deletions.
57 changes: 46 additions & 11 deletions builtin/providers/aws/resource_aws_autoscaling_group.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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

Expand All @@ -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 {
Expand Down

0 comments on commit 4df071f

Please sign in to comment.