Skip to content

Instantly share code, notes, and snippets.

@jbasdf
Last active December 10, 2018 05:13
Show Gist options
  • Save jbasdf/82ec2944c0e2e6b0cd0e10d6fa836673 to your computer and use it in GitHub Desktop.
Save jbasdf/82ec2944c0e2e6b0cd0e10d6fa836673 to your computer and use it in GitHub Desktop.
AWS EC2 Nuke
# !!!!!!!!!!!!!!!!! WARNING - Use this script at your own risk. !!!!!!!!!!!!!!!!!!!!!!!
# In the event that you need to clean out your AWS account you can use the following script to wipe out all EC2 instances and their
# related data.
# This script terminates all running EC2 instances in your account, removes the images, removes all EBS volumes and removes snapshots.
# You will need to run this with a user that has appropriate rights.
for region in us-east-2 us-east-1 us-west-1 us-west-2 ca-central-1 eu-central-1 eu-west-1 eu-west-2 ap-northeast-1 ap-southeast-1 ap-southeast-2 ap-south-1 ap-northeast-2 sa-east-1; do
echo $region
echo "Terminating Instances"
for inst in $(aws ec2 describe-instances --region=$region --filters "Name=instance-state-name,Values=pending,running,stopped,stopping" --query "Reservations[].Instances[].[InstanceId]" --output text | tr '\n' ' '); do
echo $inst
aws ec2 modify-instance-attribute --no-disable-api-termination --region=$region --instance-id $inst
aws ec2 terminate-instances --region=$region --instance-ids $inst
done
echo "Removing images"
for image in $(aws ec2 describe-images --region=$region --owners=self --query "Images[].[ImageId]" --output text | tr '\n' ' '); do
echo $image
aws ec2 deregister-image --region=$region --image-id $image
done;
echo "Removing Volumes"
for vol in $(aws ec2 describe-volumes --region=$region --query "Volumes[].[VolumeId]" --output text | tr '\n' ' '); do
echo $vol
aws ec2 delete-volume --region=$region --volume-id $vol
done;
echo "Removing Snapshots"
for snap in $(aws ec2 describe-snapshots --owner-ids=self --region=$region --query "Snapshots[].[SnapshotId]" --output text | tr '\n' ' '); do
echo $snap
aws ec2 delete-snapshot --region=$region --snapshot-id $snap
done;
echo "Removing Security Groups"
for group in $(aws ec2 describe-security-groups --region=$region --query "SecurityGroups[].[GroupId]" --output text | tr '\n' ' '); do
echo $group
aws ec2 delete-security-group --region=$region --group-id $group
done;
echo "Removing Key Pairs"
for keypair in $(aws ec2 describe-key-pairs --region=$region --query "KeyPairs[].[KeyName]" --output text | tr '\n' ' '); do
echo $keypair
aws ec2 delete-key-pair --region=$region --key-name $keypair
done;
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment