Search code examples
amazon-web-servicesboto3releaseelastic-ip

Need to release all those elastic IP that are unassociated using boto3 in All regions


I am using boto3 along with lamda to release the unused elastic IPs. Here I need to release all those IPs present in all regions of My AWS account.

def elastic_ips_cleanup():
    client = boto3.client('ec2')
    addresses_dict = client.describe_addresses()
    for eip_dict in addresses_dict['Addresses']:
        if "AssociationId" not in eip_dict:
            print (eip_dict['PublicIp'] +
                   " is not associated, releasing")
            client.release_address(AllocationId=eip_dict['AllocationId'])

I used the above codes however it only releases the IP in a particular region where I am executing the lambda function.

The expected output: It should release all the unused Elastic IPs present in all the Regions.


Solution

  • Once initialized boto3.client works only in specific region. By default the one you have in your .aws/config

    You can loop through regions and reinitilize the client with specific region passing optional argument region_name=REGION_NAME. Then rerun yuor function, apparently.

    You can use:

    import boto3
    import logging
    
    def elastic_ips_cleanup(region):
        client = boto3.client('ec2', region_name=region)
        # The rest of code you said you have tested already...
    
    
    regions = [r['RegionName'] for r in boto3.client('ec2').describe_regions()['Regions']]
    
    for region in regions:
        logging.info(f"Cleaning {region}")
        elastic_ips_cleanup(region)