如何使用Boto3在AWS Secret Manager中的特定位置存储新的秘密
问题陈述: 使用Python中的 boto3 库,在AWS Secret Manager中的特定位置存储新的秘密
更多Python相关文章,请阅读:Python 教程
解决此问题的方法/算法
- 步骤1: 导入 boto3 和 botocore 异常以处理异常。
-
步骤2: secret_stored_location 和 secret_key_pair 是必需的参数。确保 secret_key_pair 被写成 字符串 ,而不是 字典 。
-
步骤3: 使用 boto3 lib 创建AWS会话。确保默认配置文件中提到了 region_name 。如果没有提到,则在创建会话时显式传递 region_name 。
-
步骤4: 为 secretmanager 创建AWS客户端。
-
步骤5: 调用 put_secret_value 并将 secret_stored_location 作为 SecretId ,将 secret_key_pair 作为SecretString。
-
步骤6: 它返回添加新秘密的元数据。
-
步骤7: 如果添加秘密时发生了错误,则处理通用异常。
示例代码
使用以下代码在AWS Secret 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}}
极客教程