Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Boto3로 AWS Secrets Manager의 모든 시크릿 목록 조회하기

문제 정의

Python에서 boto3 라이브러리를 사용하여 AWS Secrets Manager에 저장된 모든 시크릿(secret)의 목록을 조회하는 방법을 알아보겠습니다.

해결 접근 방식 및 알고리즘

  • 1단계: 예외 처리를 위해 boto3botocore의 예외 클래스를 임포트합니다.

  • 2단계: 이 작업에는 별도의 매개변수가 필요하지 않습니다.

  • 3단계: boto3 라이브러리를 사용하여 AWS 세션을 생성합니다. 기본 프로필(default profile)에 region_name이 설정되어 있는지 확인하세요. 만약 설정되어 있지 않다면, 세션을 생성할 때 region_name을 명시적으로 전달해야 합니다.

  • 4단계: secretmanager 서비스를 위한 AWS 클라이언트를 생성합니다.

  • 5단계: list_secrets 함수를 호출하여 모든 시크릿을 조회합니다.

  • 6단계: 호출 결과로 모든 시크릿의 메타데이터가 반환됩니다.

  • 7단계: 시크릿 정보를 가져오는 도중 오류가 발생하면 일반 예외(generic exception)를 처리합니다.

예제 코드

아래 코드를 사용하면 AWS Secrets Manager에 저장된 모든 시크릿의 목록을 가져올 수 있습니다.

import boto3
from botocore.exceptions import ClientError

def get_all_secrets():
    session = boto3.session.Session()
    s3_client = session.client('secretmanager')
    try:
        response = s3_client.list_secrets()
        return response
    except ClientError as e:
        raise Exception("boto3 client error in get_all_secrets: " + e.__str__())
    except Exception as e:
        raise Exception("Unexpected error in get_all_secrets: " + e.__str__())

a = get_all_secrets()
for details in a['SecretList']:
    print(details['Name'])

실행 결과

tests/secrets
tests/aws/secrets
tests/aws/users

위 결과에서 볼 수 있듯이, list_secrets API는 계정에 저장된 모든 시크릿의 이름과 메타데이터를 반환합니다. 반환된 SecretList 키를 순회하면서 각 시크릿의 Name 값을 출력하면 저장된 시크릿 목록을 손쉽게 확인할 수 있습니다.