如何使用 Boto3 從 AWS Secrets Manager 獲取以純文字格式儲存的金鑰


問題陳述:使用 Python 中的 boto3 庫從 AWS Secrets Manager 獲取金鑰

解決此問題的方法/演算法

  • 步驟 1:匯入 boto3botocore 異常以處理異常。

  • 步驟 2: secret_stored_location 是必需的引數。它是儲存金鑰的位置。

  • 步驟 3:使用 boto3 庫建立 AWS 會話。確保在預設配置檔案中提到了 region_name。如果未提及,則在建立會話時顯式傳遞 region_name

  • 步驟 4:secretmanager 建立 AWS 客戶端。

  • 步驟 5:呼叫 get_secret_value 並將 secret_stored_location 作為 SecretId 傳遞。

  • 步驟 6:它返回給定位置中存在的未加密的所有金鑰。

  • 步驟 7:如果在檢索值時出現錯誤,則處理通用異常。

示例程式碼

使用以下程式碼從 AWS Secrets Manager 獲取純文字金鑰:

import boto3
from botocore.exceptions import ClientError

def get_secret_details(secret_stored_location):
   session = boto3.session.Session()
   s3_client = session.client('secretmanager')
   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**************"}

更新於: 2021年4月16日

915 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告