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

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


当前回答

地区= [ “eu-north-1”、“ap-south-1’,‘eu-west-3’,‘eu-west-2’, 'eu-west-1', 'ap-northeast-3', 'ap-northeast-2' 'ap-northeast-1' 'sa-east-1' 'ca-central-1', “ap-southeast-2”、“eu-central-1’,‘us-east-1’,‘us-east-2’, “us-west-1”、“us-west-2 '] 对于地区: KMS = boto3。客户端('kms', region_name= r)

其他回答

os.environ['AWS_DEFAULT_REGION'] = 'your_region_name'

对我来说,敏感很重要。

对于那些使用CloudFormation模板。可以使用UserData和AWS::Region设置环境变量AWS_DEFAULT_REGION。例如,

MyInstance1:
    Type: AWS::EC2::Instance                
    Properties:                           
        ImageId: ami-04b9e92b5572fa0d1 #ubuntu
        InstanceType: t2.micro
        UserData: 
            Fn::Base64: !Sub |
                    #!/bin/bash -x

                    echo "export AWS_DEFAULT_REGION=${AWS::Region}" >> /etc/profile

地区= [ “eu-north-1”、“ap-south-1’,‘eu-west-3’,‘eu-west-2’, 'eu-west-1', 'ap-northeast-3', 'ap-northeast-2' 'ap-northeast-1' 'sa-east-1' 'ca-central-1', “ap-southeast-2”、“eu-central-1’,‘us-east-1’,‘us-east-2’, “us-west-1”、“us-west-2 '] 对于地区: KMS = boto3。客户端('kms', region_name= r)

您还可以在脚本本身中设置环境变量,而不是传递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"]