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

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

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


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