Ashay Fernandes
Ashay Fernandes

Reputation: 383

Terraform doesn't delete auto-scaling group with scale-in protection enabled

Terraform is failing to destroy the auto-scaling group when scale in protection in turned on, is there any workaround for this?

Tried using this but under activity section of auto-scaling groups in AWS console I saw it was cancelled because scale-in protection is enabled.

provisioner "local-exec" {
    when    = destroy
    command = "aws autoscaling update-auto-scaling-group --auto-scaling-group-name ${self.name} --min-size 0 --desired-capacity 0"

  }

Upvotes: 2

Views: 1806

Answers (1)

ydaetskcoR
ydaetskcoR

Reputation: 56877

You can use the force_delete argument on the aws_autoscaling_group resource to delete the ASG without waiting for instances to be terminated. This comment on the AWS Go SDK docs explains it a little more:

    // Specifies that the group is to be deleted along with all instances associated
    // with the group, without waiting for all instances to be terminated. This
    // parameter also deletes any outstanding lifecycle actions associated with
    // the group.
    ForceDelete *bool `type:"boolean"`

Note that if you are relying on autoscaling group lifecycle hooks (such as a termination lifecycle hook that drains a container instance of any ECS tasks before the instance is terminated) then these will be skipped.

If you are relying on termination lifecycle hooks then you can instead use a destroy time provisioner to shell out to the AWS CLI like you already tried but to remove the scale in protection using the aws autoscaling set-instance-protection command:

resource "aws_autoscaling_group" "autoscaling_group" {
  # ...

  provisioner "local-exec" {
    when    = destroy
    command = <<EOF
      AUTOSCALING_INSTANCE_IDS=$(aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names ${self.name} --query 'AutoScalingGroups[0].Instances[].InstanceId' --output text)
      aws autoscaling set-instance-protection --auto-scaling-group-name ${self.name} --instance-ids "$${AUTOSCALING_INSTANCE_IDS}" --no-protected-from-scale-in
    EOF

  }
}

Upvotes: 2

Related Questions