10

When starting a new account, Amazon creates a new default VPC with 3 subnets, 1 security group, 1 ACL and 1 internet gateway. I want to delete the default vpc and objects associated with. I can do this via the console but I want to achieve this via the aws cli and I'm stucked.

When I try the following command :

aws ec2 delete-vpc --vpc-id $VpcId 

The console returns a DependencyViolation error :

A client error (DependencyViolation) occurred when calling the DeleteVpc operation: The vpc 'vpc-13f53076' has dependencies and cannot be deleted.

So I tried to delete dependencies but it doesn't works for all !

  • For the internet gateway, I got the same error :

    A client error (DependencyViolation) occurred when calling the DeleteInternetGateway operation: The internetGateway 'igw-d0f51bb5' has dependencies and cannot be deleted.

  • For the default security group. I got the following error :

    A client error (CannotDelete) occurred when calling the DeleteSecurityGroup operation: the specified group: "sg-acca7bc " name: "default" cannot be deleted by a user

  • For the default ACL, I got the following error :

    A client error (InvalidParameterValue) occurred when calling the DeleteNetworkAcl operation: cannot delete default network ACL acl-d3ba77b6

This is a new account without anything created before excepted the default vpc created by Amazon. Any help or pointers in the right direction would be much appreciated.

4 Answers 4

24

I needed to go through and delete all default VPCs across all regions, and wrote a script for it. Might save someone else some time. Requires aws cli and 'jq'.

#/usr/bin/env bash export REGIONS=$(aws ec2 describe-regions | jq -r ".Regions[].RegionName") for region in $REGIONS; do # list vpcs echo $region aws --region=$region ec2 describe-vpcs | jq ".Vpcs[]|{is_default: .IsDefault, cidr: .CidrBlock, id: .VpcId} | select(.is_default)" done read -p "Are you sure? " -n 1 -r echo # (optional) move to a new line if [[ $REPLY =~ ^[Yy]$ ]] then for region in $REGIONS ; do echo "Killing $region" # list vpcs export IDs=$(aws --region=$region ec2 describe-vpcs | jq -r ".Vpcs[]|{is_default: .IsDefault, id: .VpcId} | select(.is_default) | .id") for id in "$IDs" ; do if [ -z "$id" ] ; then continue fi # kill igws for igw in `aws --region=$region ec2 describe-internet-gateways | jq -r ".InternetGateways[] | {id: .InternetGatewayId, vpc: .Attachments[0].VpcId} | select(.vpc == \"$id\") | .id"` ; do echo "Killing igw $region $id $igw" aws --region=$region ec2 detach-internet-gateway --internet-gateway-id=$igw --vpc-id=$id aws --region=$region ec2 delete-internet-gateway --internet-gateway-id=$igw done # kill subnets for sub in `aws --region=$region ec2 describe-subnets | jq -r ".Subnets[] | {id: .SubnetId, vpc: .VpcId} | select(.vpc == \"$id\") | .id"` ; do echo "Killing subnet $region $id $sub" aws --region=$region ec2 delete-subnet --subnet-id=$sub done echo "Killing vpc $region $id" aws --region=$region ec2 delete-vpc --vpc-id=$id done done fi 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for sharing this nice piece of code that save me hours that I can spend on learning something more ;)
work like charm :)
4

Try deleting from AWS dashboard, it may give more detailed error.

  1. FYI, you cannot delete a default security group
  2. Before deleting internet gateway, detach it from VPC
  3. Make sure there is no elastic network interface (ENI) attached - You can see it under NetworkInterfaces in EC2 left pane

And why do you want to delete your default VPC?

2 Comments

As said previously, this works from the AWS console. I just want to do it from an automation script. The idea is to build a new environment only from powershell scripts using aws cli and cloudformation. I want to delete the default VPC because I don't use it, I use another one.
Its the best practice to delete the default VPC in case its not in use and there is no proper monitoring in place as it could be security risk.
1

you have to detach the gateway before you can delete it; the attachment creates a circular dependency. see my answer here.

Comments

0
##Came across this code to delete the default VPC using Boto3: import boto3 import cfnresponse import threading import logging ec2 = boto3.client('ec2') def getdefaultvpc(): vpcs = ec2.describe_vpcs( Filters=[ { 'Name': 'is-default', 'Values': [ 'true', ] }, ] ) if len(vpcs['Vpcs']) == 0: exit(0) return vpcs['Vpcs'][0] def deleteigws(vpcid): igws = ec2.describe_internet_gateways( Filters=[ { 'Name': 'attachment.vpc-id', 'Values': [ vpcid, ] }, ] ) if len(igws['InternetGateways']) > 0: igwid = igws['InternetGateways'][0]['InternetGatewayId'] attachstate = igws['InternetGateways'][0]['Attachments'][0]['State'] ec2.detach_internet_gateway( InternetGatewayId=igwid, VpcId=vpcid ) while attachstate != 'detached': igws = ec2.describe_internet_gateways( InternetGatewayIds=[ igwid ] ) if len(igws['InternetGateways'][0]['Attachments']) > 0: attachstate = igws['InternetGateways'][0]['Attachments'][0]['State'] else: attachstate = 'detached' ec2.delete_internet_gateway( InternetGatewayId=igwid ) def deletesubnets(vpcid): subnets = ec2.describe_subnets( Filters=[ { 'Name': 'vpc-id', 'Values': [ vpcid, ] }, ] ) for subnet in subnets['Subnets']: ec2.delete_subnet( SubnetId=subnet['SubnetId'] ) def main(): vpcinfo = getdefaultvpc() deleteigws(vpcinfo['VpcId']) deletesubnets(vpcinfo['VpcId']) ec2.delete_vpc( VpcId=vpcinfo['VpcId'] ) def timeout(event, context): logging.error('Execution is about to time out, sending failure response to CloudFormation') cfnresponse.send(event, context, cfnresponse.FAILED, {}, None) def lambda_handler(event, context): timer = threading.Timer((context.get_remaining_time_in_millis() / 1000.00) - 0.5, timeout, args=[event, context]) timer.start() status = cfnresponse.SUCCESS try: if event['RequestType'] == 'Create': main() except Exception as e: logging.error('Exception: %s' % e, exc_info=True) status = cfnresponse.FAILED finally: timer.cancel() cfnresponse.send(event, context, status, {}, None)`enter code here` 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.