Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.9 kB
7
Indexable
Never
#!/usr/bin/env python3
"""
This script will be used to cleanup available (not in use) ec2 volumes
"""

import logging
import os
import sys
import boto3
from botocore.exceptions import ClientError
import json

root = logging.getLogger()
root.setLevel(logging.INFO)
#root.setLevel(logging.DEBUG)

handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)
#handler.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
root.addHandler(handler)

region = os.getenv('AWS_DEFAULT_REGION', 'us-east-1')
boto3.setup_default_session(
        region_name=region
)

def get_available_volumes():
    """Check available volumes on the account"""
    ec2 = boto3.resource('ec2', region_name='us-east-1')
    volumes = ec2.volumes.filter(Filters=[{'Name': 'status', 'Values': ['available']}])
    for volume in volumes:
        volumes_list.append(volume.id)
    
    if not volumes_list:
        logging.info('<!> No volumes availabe. Nothing to do here...')
        sys.exit(0)
    else:
        number_of_volumes = len(volumes_list)
        logging.info('<!> A total of %s volumes are available and not in use!', number_of_volumes)
        logging.info('<!> This is the list of volumes that will be deleted: %s', volumes_list)

def remove_available_volumes(volumes):
    """Remove available volumes"""
    logging.info('<!> Starting deletion!')
    ec2 = boto3.client('ec2', region_name='us-east-1')
    for volume in volumes:
        try:
            response = ec2.delete_volume(
                VolumeId = volume
            )
            excluded_volumes.append(volume)
        except Exception as err:
            print(f"Unexpected {err=}, {type(err)=}")
    number_of_deleted_volumes = len(excluded_volumes)
    logging.info('<!> The following %s volumes were deleted:', number_of_deleted_volumes)
    logging.info('<!> Excluded volumes: %s', excluded_volumes)

def lambda_handler(event, context):

    volumes_list = []
    excluded_volumes = []
    volumes_list = []
    excluded_volumes = []
    environment = os.environ.get("ENVIRONMENT")

    logging.info('<!> Starting EC2 volumes cleanup...')

    try:
        get_available_volumes()

    except ClientError as e:
        if "does not exist" in e.response["Error"]["Message"]:
            print(e.response["Error"]["Message"])
        else:
            raise e

    try:
        remove_available_volumes(volumes_list)

    except ClientError as e:
        if "does not exist" in e.response["Error"]["Message"]:
            print(e.response["Error"]["Message"])
        else:
            raise e

    body = {
        "message": "Cleanup job executed successfully!",
        "input": event
    }

    response = {
        "statusCode": 200,
        "body": json.dumps(body)
    }

    return response
Leave a Comment