Skip to content

Instantly share code, notes, and snippets.

@cjp
Created March 5, 2017 15:22
Show Gist options
  • Save cjp/66cfe0c211ea601a685189aba7de6a8c to your computer and use it in GitHub Desktop.
Save cjp/66cfe0c211ea601a685189aba7de6a8c to your computer and use it in GitHub Desktop.
Delete AWS VPC including dependencies
#!/bin/sh
#
# Delete a VPC and its dependencies
if [ -z "$1" ] then
echo "usage: $0 <vpcid>"
exit 64
fi
vpcid="$1"
# Delete subnets
for i in `aws ec2 describe-subnets --filters Name=vpc-id,Values="${vpcid}" | grep subnet- | sed -E 's/^.*(subnet-[a-z0-9]+).*$/\1/'`; do aws ec2 delete-subnet --subnet-id=$i; done
# Detach internet gateways
for i in `aws ec2 describe-internet-gateways --filters Name=attachment.vpc-id,Values="${vpcid}" | grep igw- | sed -E 's/^.*(igw-[a-z0-9]+).*$/\1/'`; do aws ec2 detach-internet-gateway --internet-gateway-id=$i --vpc-id=vpc-3279eb57; done
# Delete internet gateways
for i in `aws ec2 describe-internet-gateways --filters Name=attachment.vpc-id,Values="${vpcid}" | grep igw- | sed -E 's/^.*(igw-[a-z0-9]+).*$/\1/'`; do aws ec2 delete-internet-gateway --internet-gateway-id=$i; done
# Delete security groups (ignore message about being unable to delete default security group)
for i in `aws ec2 describe-security-groups --filters Name=vpc-id,Values="${vpcid}" | grep sg- | sed -E 's/^.*(sg-[a-z0-9]+).*$/\1/' | sort | uniq`; do aws ec2 delete-security-group --group-id $i; done
# Delete the VPC
aws ec2 delete-vpc --vpc-id ${vpcid}
@blakelead
Copy link

FWIW, I use --query to do that:

for id in $(aws ec2 describe-security-groups --filters Name=vpc-id,Values="${vpcid}" --query 'SecurityGroups[*].GroupId' --output text); do
    aws ec2 delete-security-group --group-id $id
done

@cdancy
Copy link

cdancy commented Aug 27, 2021

@blakelead that's better but still won't delete security groups which are referenced by other security groups (that's a pain-in-the-butt problem to solve).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment