How to get the region of the current user from boto?

PythonAmazon Web-ServicesAmazon Ec2BotoAws Sdk

Python Problem Overview


Problem:

I'm trying to get the region of the authenticated user from boto3.

Use case:

I'm working on adding cache to https://github.com/pmazurek/aws-fuzzy-finder. I would prefer to cache the result on per-region basis.

This package uses boto to get user authentication data (keys and the region). The problem is the region is never passed explicitly by the user, its being taken from one of the many murky places that boto reads so I don't really have a way of getting it.

I have tried searching through boto3 api and googling, but couldn't find anything like a get_region or get_user_data method. Is it possible?

Python Solutions


Solution 1 - Python

You should be able to read the region_name from the session.Session object like

my_session = boto3.session.Session()
my_region = my_session.region_name

region_name is basically defined as session.get_config_variable('region')

Solution 2 - Python

Another option, if you are working with a boto3 client, is:

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

Solution 3 - Python

Took some ideas from here and other posts, and I believe this should work for pretty much any setup, whether local or on any AWS service including Lambda, EC2, ECS, Glue, etc:

def detect_running_region():
    """Dynamically determine the region from a running Glue job (or anything on EC2 for
    that matter)."""
    easy_checks = [
        # check if set through ENV vars
        os.environ.get('AWS_REGION'),
        os.environ.get('AWS_DEFAULT_REGION'),
        # else check if set in config or in boto already
        boto3.DEFAULT_SESSION.region_name if boto3.DEFAULT_SESSION else None,
        boto3.Session().region_name,
    ]
    for region in easy_checks:
        if region:
            return region

    # else query an external service
    # https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-identity-documents.html
    r = requests.get("http://169.254.169.254/latest/dynamic/instance-identity/document")
    response_json = r.json()
    return response_json.get('region')

Solution 4 - Python

None of these worked for me, as AWS_DEFAULT_REGION is not setup and client.meta.region_name gives 'us-east-1' and I don't want to use URLs. If there is already a bucket set up in that region and you are already accessing it using boto3 (note, you don't need region to access s3) then below works (as at Aug'20).

import boto3
client = boto3.client('s3')
response = client.get_bucket_location(Bucket=bucket_name)
print(response['LocationConstraint'])

Solution 5 - Python

This does not answer the OP question. The current user/session is always connected to exactly one region.

Your is the answer to: "Find out what region some bucket is in". Which is nice, but not what was asked.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPiotr MazurekView Question on Stackoverflow
Solution 1 - PythonFrederic HenriView Answer on Stackoverflow
Solution 2 - PythonSteven MillerView Answer on Stackoverflow
Solution 3 - PythonaiguoferView Answer on Stackoverflow
Solution 4 - PythonLaveshView Answer on Stackoverflow
Solution 5 - PythonJan HertsensView Answer on Stackoverflow