如何使用 Boto3 从 AWS Secret Manager 中的特定位置恢复所有密钥
awsboto3pythonserver side programmingprogramming
问题陈述:使用 Python 中的 boto3 库从 AWS Secret Manager 中的特定位置恢复所有密钥。
解决此问题的方法/算法
步骤 1:导入 boto3 和 botocore 异常来处理异常。
步骤 2: secret_stored_location 是必需参数。
步骤 3:使用 boto3 lib 创建 AWS 会话。确保在默认配置文件中提到 region_name。如果没有提及,则在创建会话时明确传递 region_name。
步骤 4: 为 secretmanager 创建 AWS 客户端。
步骤 5: 调用 restore_secret 并将 secret_stored_location 作为 SecretId 传递。
步骤 6: 返回已恢复密钥的元数据。
步骤 7: 如果在恢复密钥时出现问题,则处理一般异常。
示例代码
使用以下代码在 AWS 密钥管理器中恢复密钥 −
import boto3 from botocore.exceptions import ClientError def restore_secret_details(secret_stored_location): session = boto3.session.Session() s3_client = session.client('secretmanager') try: response = s3_client.restore_secret(SecretId=secret_stored_location) return response except ClientError as e: raise Exception("boto3 client error in restore_secret_details: " + e.__str__()) except Exception as e: raise Exception("Unexpected error in restore_secret_details: " + e.__str__()) a = restore_secret_details('/secrets/aws') print(a)
输出
{'ARN': 'arn:aws:secretsmanager:us-east-1:***************:secret:/secrets/aws-wr1Aj6', 'Name': '/secrets/aws', '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}}