【问题标题】:How to get the region of the current user from boto?如何从boto获取当前用户所在的区域?
【发布时间】:2016-09-27 15:25:39
【问题描述】:

问题:

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

用例:

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

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

我尝试通过 boto3 api 和谷歌搜索,但找不到像 get_regionget_user_data 方法这样的东西。有可能吗?

【问题讨论】:

    标签: python amazon-web-services amazon-ec2 boto aws-sdk


    【解决方案1】:

    这并不能回答 OP 问题。当前用户/会话始终只连接到一个区域。

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

    【讨论】:

      【解决方案2】:

      这些都不适合我,因为 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'])
      

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          【解决方案4】:

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

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

          【讨论】:

          • 不适用于当前实例,它只是从任何服务器返回“us-east-1”
          【解决方案5】:

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

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

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

          【讨论】:

          • 以防万一其他人将来需要这个,您需要实例化会话:sess = boto3.session.Session(); sess.region_name
          • 如果AWS_DEFAULT_REGION 未设置或您的region_name 未在~/.aws/config 中配置,这将不起作用
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-12-05
          • 2012-01-01
          • 1970-01-01
          • 2017-01-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多