如何使用 Boto3 將新的金鑰儲存到 AWS Secrets Manager 的特定位置
問題陳述: 使用 Python 中的 boto3 庫將新的金鑰儲存到 AWS Secrets Manager 的特定位置
解決此問題的方法/演算法
步驟 1: 匯入 boto3 和 botocore 異常以處理異常。
步驟 2: secret_stored_location 和 secret_key_pair 是必需的引數。確保 secret_key_pair 寫為 字串,而不是 字典。
步驟 3: 使用 boto3 庫建立 AWS 會話。確保在預設配置檔案中提到了 region_name。如果未提及,則在建立會話時顯式傳遞 region_name。
步驟 4: 為 secretmanager 建立 AWS 客戶端。
步驟 5: 呼叫 put_secret_value 並將 secret_stored_location 作為 SecretId 和 secret_key_pair 作為 SecretString 傳遞。
步驟 6: 它返回新增的新金鑰的元資料。
步驟 7: 如果在新增金鑰時出現問題,請處理通用異常。
示例程式碼
使用以下程式碼將新的金鑰儲存到 AWS Secrets Manager 中:
import boto3 from botocore.exceptions import ClientError def store_new_secret_details(secret_stored_location, secret_key_pair): session = boto3.session.Session() s3_client = session.client('secretmanager') try: response = s3_client.put_secret_value(SecretId=secret_stored_location,SecretString = secret_key_pair) return response except ClientError as e: raise Exception("boto3 client error in store_new_secret_details: " + e.__str__()) except Exception as e: raise Exception("Unexpected error in store_new_secret_details: " + e.__str__()) a = store_new_secret_details('/secrets/aws', '{"user_test2":"test2"}') print(a)
輸出
{'ARN': 'arn:aws:secretsmanager:us-east-1:***************:secret:/secrets/aws-wr1Aj6', 'Name': '/secrets/aws', 'VersionId': 'f5308bed-7c23-4d47-a32b-8f2a5f044e53', 'VersionStages': ['AWSCURRENT'], '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}}
廣告