如何使用 Boto3 從 AWS Secret Manager 中以純文字格式獲取二進位制/加密格式的金鑰


問題陳述:使用 Python 中的 boto3 庫從 AWS Secret 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:如果是加密文字,則呼叫函式使用 base64.b64decode 解碼二進位制值

  • 步驟 8:它以解密模式返回所有金鑰,即在給定位置以純文字格式返回。

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

示例程式碼

使用以下程式碼從 AWS Secret Manager 獲取解密後的純文字金鑰:

import boto3
from botocore.exceptions import ClientError

def get_decrypted_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)
   if not ('SecretString' in response):
      decoded_secret_values = base64.b64decode(response['SecretBinary'])
   return decoded_secret_values
      except ClientError as e:
         raise Exception("boto3 client error in get_decrypted_secret_details: " + e.__str__())
      except Exception as e:
         raise Exception("Unexpected error in get_decrypted_secret_details: " + e.__str__())

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

輸出

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

更新於: 2021年4月16日

599 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.