我有一个boto3客户端:

boto3.client('kms')

但这发生在新机器上,它们动态地打开和关闭。

    if endpoint is None:
        if region_name is None:
            # Raise a more specific error message that will give
            # better guidance to the user what needs to happen.
            raise NoRegionError()

为什么会这样?为什么只是部分时间?


当前回答

如果你愿意,你可以总是将它设置为EC2所在的相同区域。这是用bash,但你可以很容易地在python中重现:

EC2_AVAIL_ZONE=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone)
EC2_REGION="`echo $EC2_AVAIL_ZONE | sed -e 's:\([0-9][0-9]*\)[a-z]*\$:\\1:'`"
# if unset, set it:
export AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-$EC2_REGION}"

python:

import os
import re
from subprocess import check_output

EC2_AVAIL_ZONE = check_output(["curl", "-s", "http://169.254.169.254/latest/meta-data/placement/availability-zone"]).decode().strip()
EC2_REGION = re.sub(r"^(\w{2}-\w{3,10}-[0-9][0-9]*)[a-z]*$", r"\1", EC2_AVAIL_ZONE)
# if unset, set it:
os.environ["AWS_DEFAULT_REGION"] = os.getenv("AWS_DEFAULT_REGION", EC2_REGION)

其他回答

我相信,默认情况下,boto选择在aws cli中设置的区域。您可以运行命令#aws configure并按enter(它会显示您在aws cli with region中设置的信用)两次来确认您的区域。

如果您正在使用Linux,一种简单的方法是在~/处创建配置文件(您应该将其命名为config而不需要任何扩展名)。Aws(如果. Aws目录不存在,则在用户home ~),并在该配置文件中添加如下所示的区域。

(默认) 地区= whatever-aws-region

如果您正在使用lambda,那么您可能希望使用部署lambda的区域。 你可以使用下面的方法

import boto3
import json
import os

def lambda_handler(event, context):
    region = os.environ['AWS_REGION']
    print('Lambda region: ', region)
    kms = boto3.client('kms', region_name=region)

我们将配置好的区域存储在~/中。aws /配置文件。下面是一个纯python的方法,根据配置文件名称从这个文件中读取正确的区域:

def get_aws_region(profile_name: str) -> str:
  config = configparser.ConfigParser()
  config.read(f"{os.environ['HOME']}/.aws/config")
  profile_section = config[f"profile {profile_name}"]
  return profile_section["region"]
os.environ['AWS_DEFAULT_REGION'] = 'your_region_name'

对我来说,敏感很重要。