如何从boto获取当前用户的区域?

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

问题:

我正在尝试从 boto3 获取经过身份验证的用户的区域。

用例:

我正在努力将缓存添加到 https://github.com/pmazurek/aws-fuzzy-finder。我更愿意在 per-region 的基础上缓存结果。

此包使用 boto 获取用户身份验证数据(密钥和区域)。问题是该区域从未被用户明确传递,它是从 boto 读取的许多模糊地方之一获取的,所以我真的没有办法得到它。

我尝试通过 boto3 api 进行搜索并使用谷歌搜索,但找不到任何类似 get_regionget_user_data 方法的东西。可能吗?

您应该能够从 session.Session 对象中读取 region_name,例如

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

region_name 基本上定义为 session.get_config_variable('region')

如果您使用的是 boto3 客户端,另一个选项是:

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

从这里和其他帖子中汲取了一些想法,我相信这应该适用于几乎所有设置,无论是本地设置还是在任何 AWS 服务上,包括 Lambda、EC2、ECS、Glue 等:

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

None 这些对我有用,因为 AWS_DEFAULT_REGION 没有设置并且 client.meta.region_name 给出 'us-east-1' 并且我不想使用 URL。 如果该区域中已经设置了一个存储桶,并且您已经在使用 boto3 访问它(请注意,您不需要区域来访问 s3),那么下面的工作(截至 20 年 8 月)。

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

这没有回答 OP 问题。当前user/session始终只连接到一个区域。

您的答案是:“找出某个存储桶所在的区域”。这很好,但不是所问的。