Created
October 10, 2024 13:49
-
-
Save CuriousLearner/db798f60bafdc5cf03672b0cf8fb7be3 to your computer and use it in GitHub Desktop.
Delete ASG instances and launch configurations only for ASG using deprecated LCs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Loop through all Auto Scaling Groups (ASGs) with Launch Configurations | |
for asg in $(aws autoscaling describe-auto-scaling-groups --region us-east-1 \ | |
--query 'AutoScalingGroups[?LaunchConfigurationName!=null].AutoScalingGroupName' \ | |
--output text); do | |
echo "Deleting Auto Scaling group: $asg" | |
# Set desired capacity to 0 to terminate instances | |
aws autoscaling update-auto-scaling-group --auto-scaling-group-name "$asg" \ | |
--region us-east-1 --desired-capacity 0 | |
# Disable instance protection (optional, in case some ASGs have instance protection enabled) | |
aws autoscaling update-auto-scaling-group --auto-scaling-group-name "$asg" \ | |
--region us-east-1 --new-instances-protected-from-scale-in | |
# Wait for instances to terminate (optional: you can include this to ensure that instances are fully terminated) | |
aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names "$asg" \ | |
--region us-east-1 --query 'AutoScalingGroups[0].Instances' | |
# Delete the Auto Scaling group | |
aws autoscaling delete-auto-scaling-group --auto-scaling-group-name "$asg" \ | |
--region us-east-1 --force-delete | |
echo "$asg deleted." | |
done | |
# Now delete the associated Launch Configurations | |
for lc in $(aws autoscaling describe-launch-configurations --region us-east-1 \ | |
--query 'LaunchConfigurations[].LaunchConfigurationName' --output text); do | |
echo "Deleting Launch Configuration: $lc" | |
# Delete the Launch Configuration | |
aws autoscaling delete-launch-configuration --launch-configuration-name "$lc" \ | |
--region us-east-1 | |
echo "$lc deleted." | |
done |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
for asg in $(aws autoscaling describe-auto-scaling-groups --region us-east-1 \ | |
--query 'AutoScalingGroups[?LaunchConfigurationName!=null].AutoScalingGroupName' \ | |
--output text); do | |
# Get the number of instances in the Auto Scaling group | |
instance_count=$(aws autoscaling describe-auto-scaling-groups --region us-east-1 \ | |
--auto-scaling-group-names "$asg" \ | |
--query 'AutoScalingGroups[0].Instances | length(@)' \ | |
--output text) | |
echo "Auto Scaling group: $asg has $instance_count instances." | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment