mkreder mkreder - 7 months ago 80
Python Question

How to list all unused elastic IPs and release them using boto3

I am using boto3, I need to list all elastic IPs, find the ones that are not associated with any instance and release them.

What I am doing is:

import boto3
ec2 = boto3.resource('ec2')

Then I could list all volumes as this:

for volume in ec2.volumes.all():

Or all instances like this:

for instance in ec2.instances.all():

But I don't know how to list all elastic IPs.

The boto3 documentation lists the object ClassicAddress which is what I need to have in order to release the IP.

However, I don't know how to get a collection of all the ClassicAddresses

Answer Source

I got it working with this code:

def elastic_ips_cleanup():
    """ Cleanup elastic IPs that are not being used """
    client = boto3.client('ec2')
    addresses_dict = client.describe_addresses()
    for eip_dict in addresses_dict['Addresses']:
        if "InstanceId" not in eip_dict:
            print (eip_dict['PublicIp'] +
                   " doesn't have any instances associated, releasing")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download