如何使用 Boto3 更新 AWS Secrets Manager 中特定位置的金鑰


問題陳述: 使用 Python 中的 boto3 庫更新 AWS Secrets Manager 中特定位置的金鑰。

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

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

  • 步驟 2: secret_stored_locationsecret_key_pair 是必需的引數。確保 secret_key_pair 寫為 字串,而不是 字典

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

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

  • 步驟 5: 呼叫 update_secret 並將 secret_stored_location 作為 SecretIdsecret_key_pair 作為 SecretString 傳遞。

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

  • 步驟 7: 如果更新金鑰時出現問題,則處理通用異常。

示例程式碼

使用以下程式碼更新 AWS Secret Manager 中的金鑰:

import boto3
from botocore.exceptions import ClientError

def update_secret_details(secret_stored_location, secret_key_pair):
   session = boto3.session.Session()
   s3_client = session.client('secretmanager')
   try:
   response = s3_client.update_secret(SecretId=secret_stored_location,SecretString = secret_key_pair)
   return response
   except ClientError as e:
      raise Exception("boto3 client error in update_secret_details: " + e.__str__())
   except Exception as e:
      raise Exception("Unexpected error in update_secret_details: " + e.__str__())

a = update_secret_details('/secrets/aws', '{"user_test1":"test"}')
print(a)

輸出

{'ARN': 'arn:aws:secretsmanager:us-east-1:***************:secret:/secrets/aws-wr1Aj6', 'Name': '/secrets/aws', 'VersionId': 'f5308bed-7c23-4d47-a32b-8f2a5f044e53',  '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日

686 次瀏覽

啟動你的職業生涯

完成課程後獲得認證

開始學習
廣告
© . All rights reserved.