Last active
November 5, 2020 19:03
-
-
Save rcj4747/00bb68d1a2edd32daed1373b319533b1 to your computer and use it in GitHub Desktop.
Kill AWS instances (run daily from cron)
This file contains 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
#!/bin/bash | |
PATH=$PATH:/snap/bin | |
EC2KILL_PROFILE=${EC2KILL_PROFILE:-workpersonal} | |
PROFILE=${EC2KILL_PROFILE:+--profile $EC2KILL_PROFILE} | |
NOKILL=~/ec2nokill | |
notify-send --urgency=critical --expire-time 5000 --icon=system-restart \ | |
"EC2" \ | |
"About to kill EC2 instances, touch ${NOKILL} to prevent this." | |
#sleep 30 | |
if [ -f ${NOKILL} ] ; then | |
notify-send --urgency=low --expire-time 5000 --icon=system-restart \ | |
"EC2" \ | |
"Not killing EC2 instances today" | |
~/bin/osd "Not killing EC2 today" | |
rm ${NOKILL} | |
exit 0 | |
fi | |
echo "Killing ec2 instances..." | |
regions=$(aws ${PROFILE} ec2 describe-regions | \ | |
jq -r '.["Regions"] | .[] | .["RegionName"]' | sort -r) | |
for region in ${regions}; do | |
instances="$(aws ${PROFILE} ec2 describe-instances --region "${region}" \ | |
--filters Name=instance-state-name,Values=pending,running,shutting-down,stopping,stopped | \ | |
jq -r '.["Reservations"] | .[] | .["Instances"] | .[] | .["InstanceId"]')" | |
if [ -n "${instances}" ]; then | |
echo "Shutting down instances in ${region}": | |
for instance in ${instances}; do | |
termination_protection=$(aws ${PROFILE} ec2 --region "${region}" \ | |
describe-instance-attribute --instance-id "${instance}" \ | |
--attribute disableApiTermination | jq .DisableApiTermination.Value) | |
if [ "${termination_protection}" == "true" ]; then | |
echo "Termination protection enabled, skipping instance ${instance}" | |
continue | |
fi | |
echo "Terminating ${instance}" | |
aws ${PROFILE} ec2 --region "${region}" \ | |
terminate-instances --instance-ids "${instance}" \ | |
|| /bin/true | |
done | |
else | |
echo "No instances running in ${region}" | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment