如何使用Boto3从AWS Secret Manager中的特定位置获取密钥的详细信息

如何使用Boto3从AWS Secret Manager中的特定位置获取密钥的详细信息

问题陈述: 使用Python中的 boto3 库从AWS Secret Manager的特定位置获取密钥的详细信息。

更多Python相关文章,请阅读:Python 教程

解决此问题的方法/算法

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

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

  • 步骤3: 使用 boto3库 创建AWS会话。确保在默认配置文件中指定了 region_name 。如果没有指定,则在创建会话时显式传递 region_name

  • 步骤4:secretmanager 创建AWS客户端。

  • 步骤5: 调用 describe_secret 并将 secret_stored_location 作为 SecretId 传递。

  • 步骤6: 它返回密钥的元数据。

  • 步骤7: 如果在获取密钥详情时出现错误,则处理通用异常。

示例代码

使用以下代码从AWS Secret Manager中获取密钥的详细信息−

import boto3
from botocore.exceptions import ClientError

def get_secret_details(secret_stored_location):
   session = boto3.session.Session()
   s3_client = session.client('secretmanager')
   try:
   response = s3_client.describe_secret(SecretId=secret_stored_location)
   return response
   except ClientError as e:
      raise Exception("boto3 client error in get_secret_details: " + e.__str__())
   except Exception as e:
      raise Exception("Unexpected error in get_secret_details: " + e.__str__())

a = get_secret_details('/secrets/aws')
print(a)

输出

{'ARN': 'arn:aws:secretsmanager:us-east-1:***************:secret:/secrets/aws-wr1Aj6', 'Name': '/secrets/aws', 'LastChangedDate': datetime.datetime(2021, 4, 3, 17, 6, 57, 601000, tzinfo=tzlocal()), 'LastAccessedDate': datetime.datetime(2021, 4, 3, 5, 30, tzinfo=tzlocal()), 'VersionIdsToStages': {'f5308bed-7c23-4d47-a32b-8f2a5f044e53': ['AWSCURRENT'], 'fcdc1b5b-2a35-4d12-9d84-65d529651d2e': ['AWSPREVIOUS']}, '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': *********************************

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程