Last active
May 19, 2023 05:37
-
-
Save t0mmyt/62f4384471de83b8423f791405ee5566 to your computer and use it in GitHub Desktop.
Delete Default VPCs in AWS
This file contains hidden or 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 | |
set -euo pipefail | |
# Will only action if DRY_RUN=false | |
DRY_RUN=${DRY_RUN:=true} | |
# Will delete in the following regions | |
regions=( | |
ap-southeast-2 | |
# ap-southeast-4 | |
) | |
# get_subnets $vpc_id | |
get_subnets() { | |
local vpc_id=$1; shift | |
aws ec2 describe-subnets --filter Name=vpc-id,Values="${vpc_id}" \ | |
| jq -r '.Subnets[].SubnetId' | |
} | |
# get_igw $vpc_id | |
get_igw() { | |
local vpc_id=$1; shift | |
aws ec2 describe-internet-gateways --filter Name=attachment.vpc-id,Values="${vpc_id}" \ | |
| jq -r '.InternetGateways[].InternetGatewayId' | |
} | |
# delete_subnets ..$subnet_id | |
delete_subnets() { | |
for id in "$@"; do | |
if [ "${DRY_RUN}" == "false" ]; then | |
echo "Deleting Subnet ${id} in ${AWS_REGION}" | |
aws ec2 delete-subnet --subnet-id=${id} | |
else | |
echo "Would delete subnet ${id} in ${AWS_REGION}" | |
fi | |
done | |
} | |
# delete_igw $vpc_id ..$igw_id | |
delete_igw() { | |
vpc_id=$1; shift | |
for igw_id in "$@"; do | |
n_attachments=$(aws ec2 describe-internet-gateways --filter Name=attachment.vpc-id,Values="${vpc_id}" \ | |
| jq ".InternetGateways[] | select(.InternetGatewayId == \"${igw_id}\") | .Attachments | length") | |
if [[ ${n_attachments} == 1 ]]; then | |
if [ "${DRY_RUN}" == "false" ]; then | |
echo "Detaching IGW ${igw_id} from ${vpc_id}" | |
aws ec2 detach-internet-gateway --internet-gateway-id=${igw_id} --vpc-id="${vpc_id}" | |
else | |
echo "Would detach IGW ${igw_id} from ${vpc_id} in ${AWS_REGION}" | |
fi | |
fi | |
if [ "${DRY_RUN}" == "false" ]; then | |
echo "Deleting IGW ${igw_id}" | |
aws ec2 delete-internet-gateway --internet-gateway-id=${igw_id} | |
else | |
echo "Would delete IGW ${igw_id} in ${AWS_REGION}" | |
fi | |
done | |
} | |
# delete_vpc $vpc_id | |
delete_vpc() { | |
local id=$1; shift | |
if [ "${DRY_RUN}" == "false" ]; then | |
echo "Deleting default VPC ${id} in ${AWS_REGION}" | |
aws ec2 delete-vpc --vpc-id "${vpc_id}" | |
else | |
echo "Would delete default VPC ${id} in ${AWS_REGION}" | |
fi | |
} | |
for region in "${regions[@]}"; do | |
( | |
export AWS_REGION=${region} | |
default_vpc_id=$(aws ec2 describe-vpcs | jq -r '.Vpcs[] | select(.IsDefault) | .VpcId') | |
test -z "{$default_vpc_id}" && { | |
echo "No default VPC found in ${AWS_REGION}" | |
exit 0 | |
} | |
delete_subnets $(get_subnets "${default_vpc_id}") | |
delete_igw "${default_vpc_id}" $(get_igw "${default_vpc_id}") | |
delete_vpc "${default_vpc_id}" | |
) | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment