Skip to content

Instantly share code, notes, and snippets.

@Ari-E-S
Forked from jokeru/aws_delete-default-vpc.sh
Last active June 24, 2021 20:17
Show Gist options
  • Select an option

  • Save Ari-E-S/4024d0b34c132c4b348e7f8e20904810 to your computer and use it in GitHub Desktop.

Select an option

Save Ari-E-S/4024d0b34c132c4b348e7f8e20904810 to your computer and use it in GitHub Desktop.
Script to delete all AWS default VPCs from all regions using AWS CLI
#!/usr/bin/env bash
if [ "$AWS_PROFILE" = "" ]; then
echo "No AWS_PROFILE set"
exit 1
fi
LIVERUN=false
if [ "$1" == "confirm" ]; then
while true; do
read -p "This is a LIVE-RUN on $AWS_PROFILE! Continue? [y/N]" yn
case $yn in
[Yy]*)
LIVERUN=true
break
;;
*)
echo "Run cancelled. Nothing deleted"
exit 0
;;
esac
done
else
echo "This is a DRY-RUN on $AWS_PROFILE! Nothing will be deleted"
echo "To actually delete resources, run '$0 confirm'"
fi
printf "\n\n\n"
for region in $(aws --region us-east-1 --output text ec2 describe-regions --query '[Regions[].RegionName]'); do
echo "* Region ${region}"
# get default vpc
vpc=$(aws --region ${region} --output text ec2 describe-vpcs --filter Name=isDefault,Values=true --query 'Vpcs[0].VpcId')
if [ "${vpc}" = "None" ]; then
echo " No default vpc found"
continue
fi
echo " Found default vpc ${vpc}"
# get internet gateway
igw=$(aws --region ${region} --output text ec2 describe-internet-gateways --filter Name=attachment.vpc-id,Values=${vpc} --query 'InternetGateways[0].InternetGatewayId')
if [ "${igw}" = "None" ]; then
echo " No Internet Gateway attached to default vpc ${vpc} found"
else
echo " Detaching internet gateway ${igw}"
[[ "$LIVERUN" == "true" ]] && aws --region ${region} ec2 detach-internet-gateway --internet-gateway-id ${igw} --vpc-id ${vpc}
echo " Deleting internet gateway ${igw}"
[[ "$LIVERUN" == "true" ]] && aws --region ${region} ec2 delete-internet-gateway --internet-gateway-id ${igw}
fi
# get subnets
subnets=$(aws --region ${region} --output text ec2 describe-subnets --filters Name=vpc-id,Values=${vpc} --query '[Subnets[].SubnetId]')
if [ "${subnets}" = "None" ]; then
echo " No Subnets attached to default vpc ${vpc} found"
else
for subnet in ${subnets}; do
echo " Deleting subnet ${subnet}"
[[ "$LIVERUN" == "true" ]] && aws --region ${region} ec2 delete-subnet --subnet-id ${subnet}
done
fi
# https://docs.aws.amazon.com/cli/latest/reference/ec2/delete-vpc.html
# - You can't delete the main route table
# - You can't delete the default network acl
# - You can't delete the default security group
# delete default vpc
echo " Deleting vpc ${vpc}"
[[ "$LIVERUN" == "true" ]] && aws --region ${region} ec2 delete-vpc --vpc-id ${vpc}
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment