My Journey to the cloud…

In pursuit of excellence….


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



Leave a comment

About Me

I’m a Hands-On Technical & Entrprise Solutions Architect based out of Houston, TX. I have been working on Oracle ERP, Oracle Database and Cloud technologies for over 20 years and still going strong for learning new things.

You can connect me on Linkedin and also reach out to me

I am certified for 8x AWS, OCP (Oracle Certified Professionals), PMP, ITTL and 6 Sigma.

Disclaimer

This is a personal blog. Any views or opinions represented in this blog are personal and belong solely to the blog owner and do not represent those of people, institutions or organizations that the owner may or may not be associated with in professional or personal capacity, unless explicitly stated.
All content provided on this blog is for informational purposes only. The owner of this blog makes no representations as to the accuracy or completeness of any information on this site or found by following any link on this site.

The owner will not be liable for any errors or omissions in this information nor for the availability of this information. The owner will not be liable for any losses, injuries, or damages from the display or use of this information. Any script available on the blog post MUST be tested before they are run against Production environment.

Newsletter