如何使用 Boto3 从 AWS Secret Manager 中的特定位置删除所有密钥
问题陈述:使用Python中的boto3库从AWSSecretManager中的特定位置删除所有密钥
解决这个问题的方法/算法
第一步:导入boto3和botocore异常处理异常。
第2步:secret_stored_location是必需的参数。
步骤3:使用boto3lib创建AWS会话。确保在默认配置文件中提到region_name。如果未提及,则在创建会话时显式传递region_name。
步骤4:为secretmanager创建一个AWS客户端。
第5步:调用delete_secret并将secret_stored_location作为SecretId传递。
第6步:返回已删除机密的元数据。
第7步:如果在删除机密时出现问题,请处理通用异常。
示例代码
使用以下代码删除AWSSecretManager中的密钥-
import boto3 frombotocore.exceptionsimport ClientError def delete_secret_details(secret_stored_location): session = boto3.session.Session() s3_client = session.client('secretmanager') try: response = s3_client.create_secret(SecretId=secret_stored_location) return response except ClientError as e: raise Exception("boto3 client error in delete_secret_details: " + e.__str__()) except Exception as e: raise Exception("Unexpected error in delete_secret_details: " + e.__str__()) a = delete_secret_details('/secrets/aws') print(a)输出结果
{'ARN': 'arn:aws:secretsmanager:us-east-1:***************:secret:/secrets/aws-wr1Aj6', 'Name': '/secrets/aws', 'DeletionDate': datetime.datetime(2021, 5, 3, 15, 26, 19, 898000, tzinfo=tzlocal()), '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}}