Skip to content

Instantly share code, notes, and snippets.

@jakefhyde
Last active November 7, 2023 05:48
Show Gist options
  • Select an option

  • Save jakefhyde/5062c40b78fe8af55f16578dc74376d1 to your computer and use it in GitHub Desktop.

Select an option

Save jakefhyde/5062c40b78fe8af55f16578dc74376d1 to your computer and use it in GitHub Desktop.
clean-aws.sh
#!/bin/bash
REGION="us-east-2"
PREFIX="jhyde"
question () {
while true; do
read -p "$1" yn
case $yn in
[Yy]* ) break;;
[Nn]* ) exit;;
* ) echo "Please answer yes or no.";;
esac
done
}
echo "Finding ec2 instances"
JSON=$(aws ec2 describe-instances --region "${REGION}" --filter "Name=key-name,Values=${PREFIX}*" --query 'Reservations[*].Instances[*].[InstanceId,KeyName]' | jq '.')
echo "$JSON"
readarray -t ids < <(echo "${JSON}" | jq -c -r '.[] | .[0] | .[0]')
echo "ids: ${ids[@]}"
echo "Printing dry-run commands"
for item in "${ids[@]}"; do
echo "aws ec2 terminate-instances --region ${REGION} --instance-ids ${item}"
done
question "Run the previous commands? [yn]"
for item in "${ids[@]}"; do
aws ec2 terminate-instances --region "${REGION}" --instance-ids "${item}"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment