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

Pio*_*rek 24 python amazon-ec2 boto amazon-web-services aws-sdk

问题:

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

使用案例:

我正在努力将缓存添加到https://github.com/pmazurek/aws-fuzzy-finder.我更愿意按区域缓存结果.

该软件包使用boto获取用户身份验证数据(密钥和区域).问题是该区域永远不会被用户明确传递,它是从boto读取的许多阴暗的地方之一中获取的,所以我真的没办法得到它.

我试过搜索boto3 api和谷歌搜索,但找不到任何像一个get_regionget_user_data方法.可能吗?

Fré*_*nri 37

你应该能够region_namesession.Session像这样的对象中读取

my_session = boto3.session.Session()
my_region = my_session.region_name
Run Code Online (Sandbox Code Playgroud)

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

  • 如果未设置`AWS_DEFAULT_REGION`或未在`〜/ .aws/config中配置region_name,则无效 (13认同)
  • 为了防止其他人在将来需要这个,你需要实例化会话:`sess = boto3.session.Session(); sess.region_name` (3认同)

小智 14

如果您正在使用boto3客户端,则另一个选择是:

import boto3
client = boto3.client('s3') # example client, could be any
client.meta.region_name
Run Code Online (Sandbox Code Playgroud)

  • 不适用于当前实例,它只是从任何服务器返回“us-east-1” (5认同)

aig*_*fer 11

从这里和其他帖子中获取了一些想法,我相信这几乎适用于任何设置,无论是本地还是任何 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')
Run Code Online (Sandbox Code Playgroud)