#!/usr/bin/env bash
# NOTE: Originally taken and modified from: https://gist.github.com/mansurali901/ca7e02c520d494948c58
# modified to use region name as parameter
# (For use when you mistakenly commit your .env to github and your AWS gets flooded with 50k$/day bitcoin mining instances, like me)
# May be best to install: https://github.com/awslabs/git-secrets
# BUG(kit) - for some reason it only does 10 instances at a time. There is probably an option to do it
# USAGE:
# bash terminate-ec2-instances.sh <REGION>
region=$1
SearchCriteria () {
aws ec2 describe-instances --region ${region} --query 'Reservations[].Instances[].[InstanceId,Tags[?Key==`Name`].Value[]]' --output text | sed 's/None$/None\n/' | sed '$!N;s/\n/ /' > instances-list
cat instances-list |awk '{print $1}' >instances-list2
}
# This Section disable termination
DisableTermination () {
for instances in `cat instances-list2`
do
echo $instances
aws ec2 modify-instance-attribute --region ${region} --instance-id $instances --no-disable-api-termination
done
}
TerminateInstance () {
for i in `cat instances-list2`
do
echo "Terminating $i"
aws ec2 terminate-instances --region ${region} --instance-ids $i
done
}
SearchCriteria
DisableTermination
TerminateInstance
# clean up
rm instances-list
rm instances-list2
# regions listed below
#us-east-1
#
#US East (N. Virginia)
#
#us-east-2
#
#US East (Ohio)
#
#us-west-1
#
#US West (N. California)
#
#us-west-2
#
#US West (Oregon)
#
#ca-central-1
#
#Canada (Central)
#
#eu-central-1
#
#EU (Frankfurt)
#
#eu-west-1
#
#EU (Ireland)
#
#########eu-west-2 <--- commented as this is my region
########EU (London) <--- commented as this is my region
#
#eu-west-3
#
#EU (Paris)
#
#ap-northeast-1
#
#Asia Pacific (Tokyo)
#
#ap-northeast-2
#
#Asia Pacific (Seoul)
#
#ap-northeast-3
#
#Asia Pacific (Osaka-Local)
#
#ap-southeast-1
#
#Asia Pacific (Singapore)
#
#ap-southeast-2
#
#Asia Pacific (Sydney)
#
#ap-south-1
#
#Asia Pacific (Mumbai)
#
#sa-east-1
#
#South America (São Paulo)