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

Cách dùng Boto3 lấy khóa bí mật dạng văn bản thuần từ AWS Secrets Manager


Đề bài: Sử dụng thư viện boto3 trong Python để lấy khóa bí mật (secret keys) từ 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. Đây là nơi lưu trữ bí mật.

  • 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 get_secret_value với SecretId là secret_stored_location.

  • Bước 6: Trả về tất cả bí mật có mặt mà không mã hóa tại vị trí đã cho.

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

Mã ví dụ

Sử dụng mã sau để lấy bí mật dạng plain text:

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.get_secret_value(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['SecretString'])

Kết quả

{"aws.user":"SERVICE_USER","aws.accesskey":"I**************"}