programing

boto3 클라이언트 NoRegionError:지역 오류는 가끔만 지정해야 합니다.

bestcode 2022. 9. 4. 15:20
반응형

boto3 클라이언트 NoRegionError:지역 오류는 가끔만 지정해야 합니다.

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()

왜 이런 일이 일어나는 걸까요? 그리고 왜 일부만 일어나는 걸까요?

는 어느 합니다.kms이치노으로 사용하다, 하다, 하실 수 있습니다.region_name★★★★★★★★★★★★★★★★★★:

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

수 .~/.aws/config★★★★

[default]
region=us-west-2

또는 다음과 같이 환경변수를 사용할 수 있습니다.

export AWS_DEFAULT_REGION=us-west-2

boto3는 어느 지역을 사용해야 하는지 알려줘야 합니다.

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

저 같은 경우에는 민감성이 중요했습니다.

region_name 매개 변수를 전달하는 대신 스크립트 자체에 환경 변수를 설정할 수도 있습니다.

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

대소문자를 구분하는 경우가 있습니다.

, 는 Python 2에서 .~/.aws/config디폴트로 다른 프로파일로 정의되어 있는 경우.따라서 세션 작성에서 정의해야 합니다.

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

print(session.available_profiles)

client = session.client(
    'ec2'
)

서 나의 ★★★★★★★★★★★★★★.~/.aws/config을 사용하다

[default]
region=ap-southeast-2

[NotDefault]
region=ap-southeast-2

AWS, Personal 및 Work 로그인 시 서로 다른 프로파일을 사용하기 때문에 이 작업을 수행합니다.

람다를 사용하는 경우 람다가 배포된 영역을 사용하는 것이 좋습니다.다음을 사용할 수 있습니다.

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 cli)을 실행할 수도 있습니다.

aws configure --profile $PROFILE_NAME

그 지역을 안내할 겁니다

에 통지하다.~/.aws/config '먹다'입니다.

[default]
region = ap-southeast-1
output = json

[profile prod]
region = ap-southeast-1
output = json

괄호 안의 [profile profile name]

디폴트로는 boto가 aws cli로 설정되어 있는 지역을 선택한다고 생각합니다.#aws configure 명령을 실행하고 Enter 키를 두 번 눌러 지역을 확인할 수 있습니다.

CloudFormation 。 설정할 수 .AWS_DEFAULT_REGION 및 UserData를 한 AWS::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

regions = [
            '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']
for r in regions:
   kms = boto3.client('kms', region_name= r)

구성된 영역은 ~/.aws/config 파일에 저장되어 있습니다.다음은 프로파일 이름을 기반으로 이 파일에서 올바른 영역을 읽는 순수한 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가 특정 영역에 배포되므로 배포하는 동안 코드가 작동합니다.

언제든지 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)

언급URL : https://stackoverflow.com/questions/40377662/boto3-client-noregionerror-you-must-specify-a-region-error-only-sometimes

반응형