如何使用 Boto3 在 AWS Secrets Manager 中建立純文字金鑰


問題陳述: 使用 Python 中的 boto3 庫在 AWS Secrets Manager 中建立純文字金鑰

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

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

  • 步驟 2: secret_stored_locationsecret_key_pair 是必需的引數。它是一個儲存帶有給定鍵值對的金鑰的地方。確保 secret_key_pair 寫成 字串,而不是 字典。例如:'{key:pair}'

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

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

  • 步驟 5: 呼叫 create_secret 並將 secret_stored_location 作為 Name 引數,將 secret_key_pair 作為 SecretString 引數傳遞。

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

  • 步驟 7: 如果建立金鑰時出現錯誤,則處理通用異常。

示例程式碼

使用以下程式碼在 AWS Secrets Manager 中建立金鑰:

import boto3
from botocore.exceptions import ClientError

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

details = '{"user_test":"test"}'
a = get_decrypted_secret_details('/secrets/aws', details)
print(a)

輸出

{'ARN': 'arn:aws:secretsmanager:us-east-1:***************:secret:/secrets/aws-wr1Aj6', 'Name': '/secrets/aws', 'VersionId': 'fcdc1b5b-2a35-4d12-9d84-65d529651d2e', '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日

978 次瀏覽

啟動你的職業生涯

完成課程獲得認證

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