ข้อกำหนดปัญหา: ใช้ไลบรารี boto3 ใน Python เพื่อดึงค่า secret ที่เก็บเป็น plain text จาก AWS Secrets Manager
ขั้นตอนการแก้ปัญหา
ขั้นตอน 1: นำเข้า boto3 และ botocore.exceptions
ขั้นตอน 2: secret_stored_location เป็นพารามิเตอร์ที่จำเป็น
ขั้นตอน 3: สร้าง AWS session ด้วย boto3 พร้อมระบุ region_name
ขั้นตอน 4: สร้าง AWS client สำหรับ secretsmanager
ขั้นตอน 5: เรียก get_secret_value โดยส่ง SecretId
ขั้นตอน 6: คืนค่า secret ที่เป็น plain text (SecretString)
ขั้นตอน 7: จัดการข้อยกเว้นทั่วไป
โค้ดตัวอย่าง
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("boto3 client error in get_secret_details: " + e.__str__())
except Exception as e:
raise Exception("Unexpected error in get_secret_details: " + e.__str__())
a = get_secret_details('/secrets/aws')
print(a['SecretString'])
ผลลัพธ์
{"aws.user":"SERVICE_USER","aws.accesskey":"I**************"}
วิธีนี้ใช้สำหรับ secret ที่เก็บเป็น string โดยตรง หาก secret เป็น binary ให้ใช้วิธีในบทความก่อนหน้า (ID 1004102724)