Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách dùng Boto3 lấy chi tiết bí mật từ vị trí cụ thể trong AWS Secrets Manager


Đề bài: Sử dụng thư viện boto3 trong Python để lấy chi tiết bí mật từ một vị trí cụ thể trong AWS Secrets Manager.

Cách tiếp cận / Thuật toán

  • Bước 1: Import boto3 và botocore.exceptions để xử lý ngoại lệ.

  • Bước 2: secret_stored_location là tham số bắt buộc.

  • Bước 3: Tạo phiên làm việc AWS bằng boto3. Đảm bảo region_name được cấu hình; nếu không, truyền rõ ràng.

  • Bước 4: Tạo client AWS cho dịch vụ secretsmanager.

  • Bước 5: Gọi describe_secret với SecretId là secret_stored_location.

  • Bước 6: Trả về metadata của bí mật.

  • Bước 7: Xử lý ngoại lệ chung nếu có lỗi khi lấy chi tiết.

Mã ví dụ

Sử dụng mã sau để lấy chi tiết bí mật:

import boto3
from botocore.exceptions import ClientError

def get_secret_details(secret_stored_location):
    session = boto3.session.Session()
    s3_client = session.client('secretsmanager')
    try:
        response = s3_client.describe_secret(SecretId=secret_stored_location)
        return response
    except ClientError as e:
        raise Exception("Lỗi client boto3 trong get_secret_details: " + e.__str__())
    except Exception as e:
        raise Exception("Lỗi không mong muốn trong get_secret_details: " + e.__str__())

a = get_secret_details('/secrets/aws')
print(a)

Kết quả

{'ARN': 'arn:aws:secretsmanager:us-east-1:***************:secret:/secrets/aws-wr1Aj6', 'Name': '/secrets/aws', 'LastChangedDate': datetime.datetime(2021, 4, 3, 17, 6, 57, 601000, tzinfo=tzlocal()), 'LastAccessedDate': datetime.datetime(2021, 4, 3, 5, 30, tzinfo=tzlocal()), 'VersionIdsToStages': {'f5308bed-7c23-4d47-a32b-8f2a5f044e53': ['AWSCURRENT'], 'fcdc1b5b-2a35-4d12-9d84-65d529651d2e': ['AWSPREVIOUS']}, '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}}