如何使用 Boto3 从 AWS Secret Manager 中以纯文本格式获取二进制/加密格式的密钥
问题陈述:使用 Python 中的 boto3 库从 AWS Secret Manager 中以纯文本格式获取二进制/加密格式的密钥
解决此问题的方法/算法
步骤 1:导入 boto3 和 botocore 异常以处理异常。
步骤 2:secret_stored_location 是必需的参数。它是保存密钥的位置。
步骤 3:使用 boto3 库创建 AWS 会话。确保在默认配置文件中提到了 region_name。如果未提及,则在创建会话时显式传递 region_name。
步骤 4:为 secretmanager 创建 AWS 客户端。
步骤 5:调用 get_secret_value 并将 secret_stored_location 作为 SecretId 传递。
步骤 6:检查它是纯文本还是加密文本。
步骤 7:如果是加密文本,则调用函数使用 base64.b64decode 解码二进制值
步骤 8:它以解密模式返回所有密钥,即在给定位置以纯文本格式返回。
步骤 9:如果在检索值时出现错误,则处理通用异常。
示例代码
使用以下代码从 AWS Secret Manager 获取解密后的纯文本密钥:
import boto3
from botocore.exceptions import ClientError
def get_decrypted_secret_details(secret_stored_location):
session = boto3.session.Session()
s3_client = session.client('secretmanager')
try:
response = s3_client.get_secret_value(SecretId=secret_stored_location)
if not ('SecretString' in response):
decoded_secret_values = base64.b64decode(response['SecretBinary'])
return decoded_secret_values
except ClientError as e:
raise Exception("boto3 client error in get_decrypted_secret_details: " + e.__str__())
except Exception as e:
raise Exception("Unexpected error in get_decrypted_secret_details: " + e.__str__())
a = get_decrypted_secret_details('/secrets/aws')
print(a)输出
{"user":"SERVICE_USER","accesskey":"I**************"}
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP