Python 如何使用Boto3从AWS Secret Manager中的特定位置删除所有秘密密钥

Python 如何使用Boto3从AWS Secret Manager中的特定位置删除所有秘密密钥

问题陈述: 使用Python中的 boto3 库从AWS Secret Manager的特定位置删除所有秘密密钥。

阅读更多:Python 教程

解决此问题的方法/算法

  • 第1步: 导入 boto3botocore 异常以处理异常。

  • 第2步: secret_stored_location 是必需的参数。

  • 第3步: 使用 boto3 lib 创建AWS会话。确保在默认配置文件中提供 region_name 。如果未提供,则在创建会话时明确传递 region_name

  • 第4步:secretmanager 创建一个AWS客户端。

  • 第5步: 调用 delete_secret 并将 secret_stored_location 作为 SecretId 传递。

  • 第6步: 它返回已删除秘密的元数据。

  • 第7步: 如果在删除秘密时出现问题,请处理通用异常。

示例代码

使用以下代码删除AWS Secret Manager中的秘密:

import boto3
from botocore.exceptions import 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}}

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程