Skip to content

Instantly share code, notes, and snippets.

@davidalger
Created November 17, 2020 22:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidalger/18beebb31fe8555a84407309ab23faec to your computer and use it in GitHub Desktop.
Save davidalger/18beebb31fe8555a84407309ab23faec to your computer and use it in GitHub Desktop.
Removes internet gateways and subnets from and then deletes all default VPCs in an AWS account.
#!/usr/bin/env bash
set -euo pipefail
function error {
>&2 printf "\033[31mERROR\033[0m: $@\n"
}
INIT_ERROR=
for DEP_NAME in aws-vault jq aws; do
if ! which "${DEP_NAME}" 2>/dev/null >/dev/null; then
error "Command '${DEP_NAME}' not found. Please install."
INIT_ERROR=1
fi
done
[[ ${INIT_ERROR} ]] && exit 1
for region in $(aws ec2 describe-regions | jq -r .Regions[].RegionName); do
echo "==> Region ${region}"
vpc=$(aws ec2 --region ${region} describe-vpcs --filter Name=isDefault,Values=true | jq -r .Vpcs[0].VpcId)
if [ "${vpc}" = "null" ]; then
echo " - No default VPC found"
continue
fi
echo "Found default VPC ${vpc}"
igw=$(
aws ec2 --region ${region} describe-internet-gateways --filter Name=attachment.vpc-id,Values=${vpc} \
| jq -r .InternetGateways[0].InternetGatewayId
)
if [ "${igw}" != "null" ]; then
echo " - Detaching and deleting internet gateway ${igw}"
aws ec2 --region ${region} detach-internet-gateway --internet-gateway-id ${igw} --vpc-id ${vpc}
aws ec2 --region ${region} delete-internet-gateway --internet-gateway-id ${igw}
fi
subnets=$(aws ec2 --region ${region} describe-subnets --filters Name=vpc-id,Values=${vpc} | jq -r .Subnets[].SubnetId)
if [ "${subnets}" != "null" ]; then
for subnet in ${subnets}; do
echo " - Deleting subnet ${subnet}"
aws ec2 --region ${region} delete-subnet --subnet-id ${subnet}
done
fi
echo " - Deleting default VPC ${vpc}"
aws ec2 --region ${region} delete-vpc --vpc-id ${vpc}
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment