# This script finds and deletes all unused Elastic IPs in all AWS Regions import boto3 ec2 = boto3.resource("ec2") unused_ips = [] # Traverse regions for region in ec2.meta.client.describe_regions()["Regions"]: region_name = region["RegionName"] try: # Get all Elastic IPs in region ec2conn = boto3.client("ec2", region_name=region_name) addresses = ec2conn.describe_addresses( Filters=[{"Name": "domain", "Values": ["vpc"]}] )["Addresses"] # Check if Elastic IP is not associated with an EC2 instance, it's unused for address in addresses: if ( "AssociationId" not in address and address["AllocationId"] not in unused_ips ): # Add to list of deleted IPs ip = { "AllocationId": address["AllocationId"], "PublicIp": address["PublicIp"], "Region": region_name, } unused_ips.append(ip) print( f"Deleted unused Elastic IP {ip['PublicIp']} in region {region_name}" ) # Delete Elastic IP ec2conn.release_address(AllocationId=address["AllocationId"]) except Exception as e: print(f"No access to region {region_name}: {e}") # Print list of deleted Elastic IPs print(f"Found and deleted {len(unused_ips)} unused Elastic IPs across all regions:") print(unused_ips)