Search code examples
pythonamazon-web-servicesinstanceboto3region

Can I get region value for a given instance using boto 3 by passing on just private IP of ec2-instance


Trying to get AWS Region for particular instance. Is that possible that by passing on only ec2 instance ip to get to know its region ?

What I tried:

import boto3
client = boto3.client('s3') # example client, could be any
client.meta.region_name

but it showing same region for all servers..


Solution

  • Unfortunately, there is no native cross-region get_instance_by_private_ip API available. But, you can do something like this

    import boto3
    
    def find_region_by_private_ip_address(ip):
        ec2 = boto3.resource('ec2', 'us-east-1')
        regions = [r['RegionName'] for r in ec2.meta.client.describe_regions()['Regions']]
        for region in regions:
            ec2 = boto3.resource('ec2', region)
            instance_iterator = ec2.instances.filter(
                Filters=[
                    {
                        'Name': 'private-ip-address',
                        'Values': [
                            ip
                        ]
                    },
                ]
            )
            instance_list = list(instance_iterator)
            if len(instance_list) > 0:
                return region
    

    If performance is critical, you can do multi-threading or multi-processing to query regions in parallel.