Red Cricket
Red Cricket

Reputation: 10480

How to delete autoscaling groups with aws cli?

I am trying to write a bash script that will delete my EC2 instances and the auto scaling group that launched them:

EC2s=$(aws ec2 describe-instances --region=eu-west-3 \
  --filters "Name=tag:Name,Values=*-my-dev-eu-west-3" \
  --query "Reservations[].Instances[].InstanceId" \
  --output text)
for id in $EC2s
do
  aws ec2 terminate-instances --region=eu-west-3 --instance-ids $id
done
aws autoscaling delete-auto-scaling-group --region eu-west-3 \
  --auto-scaling-group-name my-asg-dev-eu-west-3

But it fails with this error:

An error occurred (ResourceInUse) when calling the DeleteAutoScalingGroup operation:
You cannot delete an AutoScalingGroup while there are instances or pending Spot 
instance request(s) still in the group.

There is no issue if I use the AWS console to do the same thing. Why does the aws cli prevent me from deleting the ASG if I have terminated all the instances?

Upvotes: 0

Views: 1142

Answers (3)

Sachin Singh
Sachin Singh

Reputation: 41

You can force delete the ASG with active spot instance requests with AWS cli:

aws autoscaling delete-auto-scaling-group --auto-scaling-group-name Your-ASG-Name --force-delete

Upvotes: 0

Asdfg
Asdfg

Reputation: 12273

if you really want to do this with CLI, you may first want to use aws autoscaling suspend-processes command to prevent ASG from creating new instances. Then use aws ec2 terminate-instances like you are doing. Then use aws ec2 wait instance-terminated command and pass instance ids. Once all that is done, you should be able use aws autoscaling delete-auto-scaling-group

Upvotes: 2

Mark B
Mark B

Reputation: 201103

aws ec2 terminate-instances will return before the instances have finished terminating (which could take several minutes).

I highly recommend using something like CloudFormation or Terraform for this sort of thing instead of the AWS CLI tool.

Upvotes: 2

Related Questions