Skip to content

Instantly share code, notes, and snippets.

@JohnPreston
Created May 23, 2019 08:13
Show Gist options
  • Select an option

  • Save JohnPreston/9afdd88973a88b51e698f85ba306abd1 to your computer and use it in GitHub Desktop.

Select an option

Save JohnPreston/9afdd88973a88b51e698f85ba306abd1 to your computer and use it in GitHub Desktop.

Revisions

  1. JohnPreston created this gist May 23, 2019.
    36 changes: 36 additions & 0 deletions aws_delete_default_vpc.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    #!/usr/bin/env bash

    for region in $(aws ec2 describe-regions --region eu-west-1 | jq -r .Regions[].RegionName); do

    echo "* Region ${region}"

    # get default vpc
    vpc=$(aws ec2 --region ${region} describe-vpcs --filter Name=isDefault,Values=true | jq -r .Vpcs[0].VpcId)
    if [ "${vpc}" = "null" ]; then
    echo "No default vpc found"
    continue
    fi
    echo "Found default vpc ${vpc}"
    igw=$(aws ec2 --region ${region} describe-internet-gateways --filter Name=attachment.vpc-id,Values=${vpc} \
    | jq -r .InternetGateways[0].InternetGatewayId)
    if [ "${igw}" != "null" ]; then
    echo "Detaching and deleting internet gateway ${igw}"
    aws ec2 --region ${region} \
    detach-internet-gateway --internet-gateway-id ${igw} --vpc-id ${vpc}
    aws ec2 --region ${region} \
    delete-internet-gateway --internet-gateway-id ${igw}
    fi
    # get subnets
    subnets=$(aws ec2 --region ${region} describe-subnets --filters Name=vpc-id,Values=${vpc} \
    | jq -r .Subnets[].SubnetId)
    if [ "${subnets}" != "null" ]; then
    for subnet in ${subnets}; do
    echo "Deleting subnet ${subnet}"
    aws ec2 --region ${region} \
    delete-subnet --subnet-id ${subnet}
    done
    fi
    echo "Deleting vpc ${vpc}"
    aws ec2 --region ${region} \
    delete-vpc --vpc-id ${vpc}
    done