Created
February 24, 2020 23:23
-
-
Save jghaines/767ecfb463300eab1df12c074cc2adbd to your computer and use it in GitHub Desktop.
Delete Default VPC Resources
This file contains 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
#!/usr/bin/env python | |
import argparse | |
import boto3 | |
import sys | |
from botocore.exceptions import ClientError | |
EXCLUDE_REGIONS = [ 'us-gov-west-1', 'cn-north-1' ] # don't try to delete VPCs in these regions | |
class DefaultVpc(object): | |
def __init__(self, region, args): | |
self.client = boto3.client( | |
'ec2', | |
region_name=region, | |
aws_access_key_id=args.aws_access_key_id, | |
aws_secret_access_key=args.aws_secret_access_key, | |
aws_session_token=args.aws_session_token | |
) | |
def get(self, resource='vpc'): | |
if resource == 'vpc': | |
return self.client.describe_vpcs( | |
Filters=[{ | |
'Name' : 'isDefault', | |
'Values' : [ | |
'true', | |
] | |
}] | |
)['Vpcs'] | |
elif resource == 'igw': | |
return self.client.describe_internet_gateways( | |
Filters=[{ | |
'Name' : 'attachment.vpc-id', | |
'Values' : [ | |
self.get()[0]['VpcId'], | |
] | |
}] | |
)['InternetGateways'] | |
elif resource == 'subnets': | |
return self.client.describe_subnets( | |
Filters=[{ | |
'Name' : 'defaultForAz', | |
'Values' : [ | |
'true', | |
] | |
}] | |
)['Subnets'] | |
def delete(self): | |
vpc = self.get() | |
if len(vpc) > 0: | |
# detach and delete internet gateway | |
igw = self.get('igw') | |
if len(igw) > 0: | |
sys.stdout.write("Detaching Internet GateWay(%s) from VPC(%s)... " %(igw[0]['InternetGatewayId'], vpc[0]['VpcId'])) | |
try: | |
self.client.detach_internet_gateway( | |
InternetGatewayId=igw[0]['InternetGatewayId'], | |
VpcId=vpc[0]['VpcId'] | |
) | |
except ClientError as e: | |
sys.stdout.write("failed.\n") | |
sys.stderr.write(e) | |
sys.exit(1) | |
else: | |
sys.stdout.write("done.\n") | |
sys.stdout.write("Deleting Internet GateWay(%s)... " %igw[0]['InternetGatewayId']) | |
try: | |
self.client.delete_internet_gateway( | |
InternetGatewayId=igw[0]['InternetGatewayId'] | |
) | |
except ClientError as e: | |
sys.stdout.write("failed.\n") | |
sys.stderr.write(e) | |
sys.exit(2) | |
else: | |
sys.stdout.write("done.\n") | |
# delete subnets | |
subnets = self.get('subnets') | |
if len(subnets) > 0: | |
for subnet in subnets: | |
sys.stdout.write("Deleting Subnet(%s)... " %subnet['SubnetId']) | |
try: | |
self.client.delete_subnet( | |
SubnetId=subnet['SubnetId'] | |
) | |
except ClientError as e: | |
sys.stdout.write("failed.\n") | |
sys.stderr.write(e) | |
sys.exit(3) | |
else: | |
sys.stdout.write("done.\n") | |
# delete vpc | |
sys.stdout.write("Deleting VPC(%s)... " %vpc[0]['VpcId']) | |
try: | |
self.client.delete_vpc( | |
VpcId=vpc[0]['VpcId'] | |
) | |
except ClientError as e: | |
sys.stdout.write("failed.\n") | |
sys.stderr.write(e) | |
sys.exit(4) | |
else: | |
sys.stdout.write("done.\n") | |
return | |
sys.stdout.write('No Default VPC found...\n') | |
return | |
def get_vpc_regions(): | |
ec2_client = boto3.client('ec2', region_name='us-east-1') | |
return map( lambda region: region['RegionName'], ec2_client.describe_regions()['Regions'] ) | |
def get_cli_args(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument('--aws-access-key-id', action = 'store', required=False, metavar='AWS_ACCESS_KEY_ID', dest='aws_access_key_id', default=None, help='AWS access key.' ) | |
parser.add_argument('--aws-secret-access-key', action = 'store', required=False, metavar='AWS_SECRET_ACCESS_KEY', dest='aws_secret_access_key', default=None, help='AWS secret key.' ) | |
parser.add_argument('--aws-session-token', action = 'store', required=False, metavar='AWS_SESSION_TOKEN', dest='aws_session_token', default=None, help='Specify a session token if you are using temporary security credentials.' ) | |
parser.add_argument('--dry-run', action = 'store_true', required=False, dest='dry_run', default=False, help='.' ) | |
group = parser.add_mutually_exclusive_group(required=True) | |
group.add_argument('--all-regions', action = 'store_true', dest='all_regions', help='AWS access key.' ) | |
group.add_argument('--region', action = 'store', metavar='AWS_REGION_NAME', dest='region', help='AWS region.' ) | |
return parser.parse_args() | |
if __name__ == '__main__': | |
args = get_cli_args() | |
if args.all_regions: | |
regions = get_vpc_regions() | |
else: | |
regions = [ args.region ] | |
for region in regions: | |
sys.stderr.write("Deleting Default VPC in Region: {}\n".format(region)) | |
vpc = DefaultVpc(region, args) | |
vpc.delete() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment