Clean up unused Elastic IP addresses across all AWS Regions


Elastic IP addresses (EIPs) in Amazon Web Services (AWS) are a useful resource for static public IP addresses that you can allocate to your AWS resources, such as EC2 instances, NAT Gateways, and Elastic Load Balancers.

However, over time, unused EIPs can accumulate and add unnecessary costs to your AWS bill.

In this blog post, we will show you how to create a Python script using the AWS Boto3 library to delete all unused EIPs across all AWS regions.

How to delete all unused Elastic IP addresses across all AWS Regions

Before you can start, you’re required to have done the following prerequisites before you can run the Python script on your AWS account.

  1. Install the AWS CLI and configure an AWS profile
  2. Setting up the Python Environment

If you’ve already done this, you can proceed to step 3.

1. Install AWS CLI and configure an AWS profile

The AWS CLI is a command line tool that allows you to interact with AWS services in your terminal.

Depending on if you’re running LinuxmacOS, or Windows the installation goes like this:

# macOS install method:
brew install awscli

# Windows install method:
wget https://awscli.amazonaws.com/AWSCLIV2.msi
msiexec.exe /i https://awscli.amazonaws.com/AWSCLIV2.msi

# Linux (Ubuntu) install method:
sudo apt install awscli

In order to access your AWS account with the AWS CLI, you first need to configure an AWS Profile. There are 2 ways of configuring a profile:

  • Access and secret key credentials from an IAM user
  • AWS Single Sign-on (SSO) user

In this article, I’ll briefly explain how to configure the first method so that you can proceed with running the python script on your AWS account.

If you wish to set up the AWS profile more securely, then I’d suggest you read and apply the steps described in setting up AWS CLI with AWS Single Sign-On (SSO).

In order to configure the AWS CLI with your IAM user’s access and secret key credentials, you need to login to the AWS Console.

Go to IAM > Users, select your IAM user, and click on the Security credentials tab to create an access and secret key.

Then configure the AWS profile on the AWS CLI as follows:

➜ aws configure
AWS Access Key ID [None]: <insert_access_key>
AWS Secret Access Key [None]: <insert_secret_key>
Default region name [None]: <insert_aws_region>
Default output format [json]: json

Your was credentials are stored in ~/.aws/credentials and you can validate that your AWS profile is working by running the command:

➜ aws sts get-caller-identity
{
    "UserId": "AIDA5BRFSNF24CDMD7FNY",
    "Account": "012345678901",
    "Arn": "arn:aws:iam::012345678901:user/test-user"
}

2. Setting up the Python Environment

To be able to run the Python Boto3 script, you will need to have Python installed on your machine.

Depending on if you’re running LinuxmacOS, or Windows the installation goes like this:

# macOS install method:
brew install python

# Windows install method:
wget https://www.python.org/ftp/python/3.11.2/python-3.11.2-amd64.exe
msiexec.exe /i https://www.python.org/ftp/python/3.11.2/python-3.11.2-amd64.exe

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py

# Linux (Ubuntu) install method:
sudo apt install python3 python3-pip

Once you have installed Python, you will need to install the Boto3 library. You can install Boto3 using pip, the Python package manager, by running the following command in your terminal:

pip install boto3

3. Create the Python script to delete all unused Elastic IP addresses across AWS Regions

Once you have our environment set up, you can create the Python script.

Copy the following code into a new file on the desired location and name it: delete_all_unused_elastic_ips.py.

#  https://github.com/dannysteenman/aws-toolbox
#
#  License: MIT
#
# This script finds and deletes all unused Elastic IPs in all AWS Regions

import boto3

ec2 = boto3.resource("ec2")

unused_ips = {}

for region in ec2.meta.client.describe_regions()["Regions"]:
    region_name = region["RegionName"]
    try:
        ec2conn = boto3.client("ec2", region_name=region_name)
        addresses = ec2conn.describe_addresses(
            Filters=[{"Name": "domain", "Values": ["vpc"]}]
        )["Addresses"]
        for address in addresses:
            if (
                "AssociationId" not in address
                and address["AllocationId"] not in unused_ips
            ):
                unused_ips[address["AllocationId"]] = region_name
                ec2conn.release_address(AllocationId=address["AllocationId"])
                print(
                    f"Deleted unused Elastic IP {address['PublicIp']} in region {region_name}"
                )
    except Exception as e:
        print(f"No access to region {region_name}: {e}")

print(f"Found and deleted {len(unused_ips)} unused Elastic IPs across all regions:")
print(unused_ips)

The Python script runs the following steps in order to delete the unused EIPs:

  1. Get all the regions available in the AWS account
  2. For each region, get all the allocated EIPs
  3. For each EIP, check if it is associated with any AWS resource
  4. If the EIP is not associated with any AWS resource, then release it

4. Run the Python Boto3 script on your AWS account

To run the Python script, open a terminal and navigate to the directory where the delete_all_unused_elastic_ips.py file is saved.

Then, run the following command:

python delete_all_unused_elastic_ips.py

After running the command, the script will start iterating over all the regions available in your AWS account.

For each region, it will list all the unused EIPs and delete them, as shown in the example output below.

➜ python ec2/delete_all_unused_elastic_ips.py

Deleted unused Elastic IP 18.157.113.139 in region eu-central-1
Deleted unused Elastic IP 3.66.241.7 in region eu-central-1
Deleted unused Elastic IP 3.77.49.42 in region eu-central-1
Deleted unused Elastic IP 3.213.93.51 in region us-east-1
Deleted unused Elastic IP 3.230.217.191 in region us-east-1

Found and deleted 5 unused Elastic IPs across all regions:

{'eipalloc-0f6679263bdc6ad6e': 'eu-central-1', 'eipalloc-0bf6d914945dae5b0': 'eu-central-1', 'eipalloc-0ec89d1a96ddc814c': 'eu-central-1', 'eipalloc-04d63dab54be821e0': 'us-east-1', 'eipalloc-07eea6853bad3718b': 'us-east-1'}

Conclusion

In this blog post, we have shown you how to create a Python script using the AWS Boto3 library to delete all unused Elastic IP addresses across all AWS regions.

By regularly running this script, you can save costs and keep your AWS resources organized.




Danny Steenman

A Senior AWS Cloud Engineer with over 9 years of experience migrating workloads from on-premises to AWS Cloud.

I have helped companies of all sizes shape their cloud adoption strategies, optimizing operational efficiency, reducing costs, and improving organizational agility.

Connect with me today to discuss your cloud aspirations, and let’s work together to transform your business by leveraging the power of AWS Cloud.

I need help with..
stacked cubes
Improving or managing my CDK App.Maximize the potential of your AWS CDK app by leveraging the expertise of a seasoned CDK professional.
Reducing AWS Costs.We can start by doing a thorough assessment of your current AWS infrastructure, identifying areas with potential for cost reduction and efficiency improvement.
Verifying if my infrastructure is reliable and efficient.We’ve created a comprehensive AWS Operations Checklist that you can utilize to quickly verify if your AWS Resources are set up reliably and efficiently.