我有一个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()

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


当前回答

对于python2,我发现boto3库并没有从~/。如果区域定义在与default不同的配置文件中,则使用Aws /config。 所以你必须在会话创建中定义它。

session = boto3.Session(
    profile_name='NotDefault',
    region_name='ap-southeast-2'
)

print(session.available_profiles)

client = session.client(
    'ec2'
)

我的~/。Aws /配置文件是这样的:

[default]
region=ap-southeast-2

[NotDefault]
region=ap-southeast-2

我这样做是因为我使用不同的配置文件登录AWS,个人和工作。

其他回答

您必须以某种方式告诉boto3您希望在哪个区域创建kms客户端。这可以显式地使用region_name参数来完成,如下所示:

kms = boto3.client('kms', region_name='us-west-2')

或者您可以在~/中有一个与您的配置文件相关联的默认区域。Aws /配置文件如下:

[default]
region=us-west-2

或者你可以使用环境变量,如下所示:

export AWS_DEFAULT_REGION=us-west-2

但是您需要告诉boto3使用哪个区域。

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

您还可以在脚本本身中设置环境变量,而不是传递region_name参数

操作系统。environ['AWS_DEFAULT_REGION'] = 'your_region_name'

大小写敏感性可能很重要。

我们将配置好的区域存储在~/中。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"]

如果您使用AWS Lambda,您的代码将在部署时工作, 因为Lambda被部署在特定的区域。