Created
January 23, 2024 20:40
-
-
Save leonardobiffi/d7840a000bc4d78efcd708a89031dc69 to your computer and use it in GitHub Desktop.
Script to delete AWS default VPCs from regions using AWS CLI
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
#!/usr/bin/env bash | |
REGIONS='us-east-1 | |
us-east-2' | |
INDENT=' ' | |
echo "Using profile $AWS_PROFILE" | |
for region in $REGIONS; do | |
export AWS_REGION=$region | |
echo "* Region $region" | |
# get default vpc | |
vpc=$(aws ec2 describe-vpcs --filter Name=isDefault,Values=true --output text --query 'Vpcs[0].VpcId') | |
if [ "${vpc}" = "None" ]; then | |
echo "${INDENT}No default vpc found" | |
continue | |
fi | |
echo "${INDENT}Found default vpc ${vpc}" | |
# get internet gateway | |
igw=$(aws ec2 describe-internet-gateways --filter Name=attachment.vpc-id,Values=${vpc} --output text --query 'InternetGateways[0].InternetGatewayId') | |
if [ "${igw}" != "None" ]; then | |
echo "${INDENT}Detaching and deleting internet gateway ${igw}" | |
aws ec2 detach-internet-gateway --internet-gateway-id ${igw} --vpc-id ${vpc} | |
aws ec2 delete-internet-gateway --internet-gateway-id ${igw} | |
fi | |
# get subnets | |
subnets=$(aws ec2 describe-subnets --filters Name=vpc-id,Values=${vpc} --output text --query 'Subnets[].SubnetId') | |
if [ "${subnets}" != "None" ]; then | |
for subnet in ${subnets}; do | |
echo "${INDENT}Deleting subnet ${subnet}" | |
aws 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 "${INDENT}Deleting vpc ${vpc}" | |
aws 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