Skip to content

Instantly share code, notes, and snippets.

@metacurb
Last active August 19, 2019 15:42
Show Gist options
  • Save metacurb/e8bf73fc7582a0e5b78e48ca84cacc65 to your computer and use it in GitHub Desktop.
Save metacurb/e8bf73fc7582a0e5b78e48ca84cacc65 to your computer and use it in GitHub Desktop.
Delete all AWS EC2 instances in all regions via Windows Powershell
$regions = aws ec2 describe-regions --query Regions[*].[RegionName] --output text
foreach ($region in $regions) {
Write-Output "Terminating Instances in region: '$region'..."
aws configure set region $region
$ids = aws ec2 describe-instances --query "Reservations[*].Instances[*].{ID:InstanceId}" --output text --region $region
$idArray = $ids.Split([Environment]::NewLine)
foreach($id in $idArray) {
aws ec2 modify-instance-attribute --no-disable-api-termination --instance-id $id --region $region
aws ec2 terminate-instances --instance-ids $id
}
}
@metacurb
Copy link
Author

Through my own negligence and naivety, my AWS account became compromised. The lucky hacker managed to create 236 x EC2 Instances and 268 x EBS Volumes, racking up about $1000 in my billing. I took to removing the instances manually, but had to go through the process of turning off termination protection in the UI, before terminating the instance.

This was slow, tedious, and after about 4 instances I got annoyed.

This script can be run via Powershell to kill off every one of your instances in every region. As a pre-requisite, you'll need to have the AWS CLI pre-installed, and have your AWS account configured via aws configure.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment