Automate Cleaning of Unused EIP Through Lambda Part1

muash10

Muhammed Ashraf

Posted on October 2, 2024

Automate Cleaning of Unused EIP Through Lambda Part1

Overview

The cost on AWS is considered one of the important things that everyone should take care of. It will be a headache if you have many resources on your account and a lot of charges occur.

Sometimes, most of the charges are due to forgetting a running resource like an EC2 instance or forgetting to delete unused resources such as EBS or EIP.

EBS and EIP charge you if they are provisioned and created on your account, whether used or not.

Previously in this article, we discussed how to delete unattached EBS volumes to save you some costs. In this article, I will help you to delete unused EIPs and how to Automate this part in order to avoid charges for unnecessary EIPs.

High Level Design

Image description

Steps:

we will utilize EventBridge new feature which is schedule to trigger our Lambda function every 1 day

1- We will create a Lambda function default configuration as below with runtime python 3.12 and an execution role to VPC full access

Image description

This is my python code I wrote in order to release unused EIPs

import json
import boto3

def lambda_handler(event, context):
    ec2_resource = boto3.resource('ec2')

    elastic_ips_list = []
    for elastic_ips in ec2_resource.vpc_addresses.all():
        try:
            if elastic_ips.instance_id is None:
               elastic_ips_list.append(elastic_ips)
               print(f"Releasing the Unused Addresses \n")
               elastic_ips.release()
               print("IPs addresses released")
        except Exception as e:
            print(f"Error releasing IP Address {elastic_ip.public_ip}: {str(e)}")

    return {
        'body': json.dumps("The list of Unused Addresses is: " + str(elastic_ips_list))
    }
Enter fullscreen mode Exit fullscreen mode

2- We will create EventBridge schedule with the below configurations in order to trigger our lambda function

Image description

Image description

Image description

Image description

Image description

Image description

Image description

After the EventBridge schedule configured it will be ready to invoke our lambda function with the rate configured, the Lambda function will list the EIPs and will check for the unassociated ones to delete them, in the next article we will configure our lambda function to send an email with the deleted EIPs through AWS SNS.

Closing Words

Monitoring your AWS cost is crucial to avoid any unnecessary charges, so always try to have checks on your resources to see what resources are unused in order to start deleting them. It's better to automate this task through a combination of EventBridge schedules and Lambda functions.

💖 💪 🙅 🚩
muash10
Muhammed Ashraf

Posted on October 2, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related