Skip to content

Instantly share code, notes, and snippets.

@cjp
Created March 5, 2017 15:22
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • 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}
@RichardBronosky
Copy link

2 major issues:

  1. Line 5 needs to have a ; between ] and then
  2. Line 15 has your VPC ID hardcoded in it instead of using the $vpcid variable

I would also suggest:

  1. Use #!/bin/bash -eu
    • It's not worth trying to make generic Posix script.
    • It's best to not have scripts continue when they encounter an error or try to use an undefined variable.
  2. Put a || true at the end of your delete-security-group command because trying to delete the default security group gives an error.

@munishase
Copy link

can you help me by providing a script that can delete all vpc, including its all dependencies, in any region for my login in aws?

@AkiraKane
Copy link

In my case, we also need to delete the route table (custom one) before deleting the vpc.

@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