如何使用 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:呼叫 describe_secret 並將 secret_stored_location 作為 SecretId 傳遞。

  • 步驟 6:它返回金鑰的元資料。

  • 步驟 7:如果在獲取金鑰詳細資訊時出現錯誤,則處理通用異常。

示例程式碼

使用以下程式碼獲取 AWS Secret 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.describe_secret(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)

輸出

{'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}}

更新於: 2021年4月16日

1K+ 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告