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

Solution 1:

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:

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:

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:

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'])