Home > AWS/Boto3/Python > Boto3 script to delete existing VPC Interface Endpoints from a given AWS Account

Boto3 script to delete existing VPC Interface Endpoints from a given AWS Account

Recently developed a script using Boto3 and Python to delete specific VPC Interface Endpoints. These endpoints were deployed as part of landing zone resources but are not being used currently. Such resources incur cost and hence if not used, it is good to remove them to save some cost.

Intent is to call this script from some DevOps tool (like Ansible or Jenkins) to complete automate the task.

#!/usr/bin/env python

import boto3
import logging
import os.path
import time
import argparse



output_dir = "/tmp"
DEFAULT_AWS_Account_ID = "1111222222"
DEFAULT_REGION = "us-east-1"

client = boto3.client('ec2')

logger = logging.getLogger()
logger.setLevel(logging.INFO)

# create console handler and set level to info
handler = logging.StreamHandler()
handler.setLevel(logging.INFO)
logger.addHandler(handler)

# create file handler and set level to Info
# this is to help Output directed to both - console 
# and file
handler = logging.FileHandler(os.path.join(output_dir, "vpcendpointdelete.log"),"w", encoding=None, delay="true")
handler.setLevel(logging.INFO)
logger.addHandler(handler)



def parse_commandline_arguments():

    global REGION
    global AWS_Account_ID

    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter,
                                     description='Boto3 script to delete VPC Interface Endppints from a given AWS Account.')
    parser.add_argument("-accountID", "--ownerID", dest="aws_ID", type=str, default=DEFAULT_AWS_Account_ID,
                        help="The AWS Account ID where VPC Endpoint is to be deleted")
    parser.add_argument("-r", "--region", dest="region", type=str,
                        default=DEFAULT_REGION, help="Specify the region of the AWS Account")

    args = parser.parse_args()
    REGION = args.region
    AWS_Account_ID = args.aws_ID



def remove_vpcendpoint(region):
    if region == "us-east-2":
        filters = [{'Name': 'service-name', 'Values': ['com.amazonaws.us-east-2.ec2','com.amazonaws.us-east-2.ec2messages','com.amazonaws.us-east-2.ssm','com.amazonaws.us-east-2.ssmmessages','com.amazonaws.us-east-2.monitoring'] }, {'Name': 'vpc-endpoint-type', 'Values' : ['Interface']}]
    if region == "us-east-1":
        filters = [{'Name': 'service-name', 'Values': ['com.amazonaws.us-east-1.ec2','com.amazonaws.us-east-1.ec2messages','com.amazonaws.us-east-1.ssm','com.amazonaws.us-east-1.ssmmessages','com.amazonaws.us-east-1.monitoring'] }, {'Name': 'vpc-endpoint-type', 'Values' : ['Interface']}]
   
    response = client.describe_vpc_endpoints(Filters=filters)
    for services in response['VpcEndpoints']:
        logger.info("Deleting VpcEndpoint ID : {} - Service Name : {}".format(services['VpcEndpointId'],services['ServiceName']))
        for attempt in range(5):
            try:
                client.delete_vpc_endpoints(
                    VpcEndpointIds=[services['VpcEndpointId']]
                    )
            except BaseException as err:
                logger.error(err)
                logger.info("*** ERROR *** during VPC Interface Endpoint delete - retry...")
                time.sleep(0.5)
            else:
                logger.info("--> Done")
                break;
        else:
            logger.error("*** ERROR *** - All attempt to delete VPC Interface Endpoint failed - exit with error")
            raise Exception("*** ERROR *** - Can't delete VPC Interface Endpoint")


if __name__ == '__main__':
    try:
        parse_commandline_arguments()
        remove_vpcendpoint(REGION)
    except Exception as error:
        logging.error(error)
        print(str(error))
		

Enjoy reading !!!
Anand M

Categories: AWS/Boto3/Python Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: