Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Boto3를 사용하여 AWS Secret Manager의 특정 위치에 새 암호를 저장하는 방법

<시간/>

문제 설명: boto3 사용 AWS Secret Manager의 특정 위치에 새 암호를 저장하는 Python 라이브러리

이 문제를 해결하기 위한 접근 방식/알고리즘

  • 1단계: boto3 가져오기 및 보토코어 예외를 처리하는 예외.

  • 2단계: secret_stored_locationsecret_key_pair 필수 매개변수입니다. secret_key_pair 확인 문자열로 작성됩니다. , 딕셔너리가 아님 .

  • 3단계: boto3 lib를 사용하여 AWS 세션 생성 . region_name을(를) 확인하십시오. 기본 프로필에 언급되어 있습니다. 언급되지 않은 경우 region_name을 명시적으로 전달합니다. 세션을 만드는 동안.

  • 4단계: secretmanager용 AWS 클라이언트 생성 .

  • 5단계: put_secret_value 호출 secret_stored_location 전달 SecretId로 및 secret_key_pair SecretString으로.

  • 6단계: 추가된 새로운 비밀의 메타데이터를 반환합니다.

  • 7단계: 비밀을 추가하는 동안 문제가 발생한 경우 일반 예외를 처리합니다.

예시 코드

다음 코드를 사용하여 AWS Secret Manager에 새 암호를 저장하십시오 -

import boto3
from botocore.exceptions import ClientError

def store_new_secret_details(secret_stored_location, secret_key_pair):
   session = boto3.session.Session()
   s3_client = session.client('secretmanager')
   try:
   response = s3_client.put_secret_value(SecretId=secret_stored_location,SecretString = secret_key_pair)
   return response
   except ClientError as e:
      raise Exception("boto3 client error in store_new_secret_details: " + e.__str__())
   except Exception as e:
      raise Exception("Unexpected error in store_new_secret_details: " + e.__str__())

a = store_new_secret_details('/secrets/aws', '{"user_test2":"test2"}')
print(a)

출력

{'ARN': 'arn:aws:secretsmanager:us-east-1:***************:secret:/secrets/aws-wr1Aj6', 'Name': '/secrets/aws', 'VersionId': 'f5308bed-7c23-4d47-a32b-8f2a5f044e53', 'VersionStages': ['AWSCURRENT'],   'ResponseMetadata': {'RequestId': 'b32fe48d**************ab', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Sat, 03 Apr 2021 09:40:48 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '197', 'connection': 'keep-alive', 'x-amzn-requestid': *********************************}, 'RetryAttempts': 0}}