如何使用 Boto3 从 AWS Secret Manager 中的二进制/加密格式以纯文本形式获取密钥
问题陈述:使用Python中的boto3库从AWSSecretManager中存在的二进制/加密格式中以纯文本形式获取密钥
解决这个问题的方法/算法
第一步:导入boto3和botocore异常处理异常。
第2步:secret_stored_location是必需的参数。这是一个保存秘密的地方。
步骤3:使用boto3lib创建AWS会话。确保在默认配置文件中提到region_name。如果未提及,则在创建会话时显式传递region_name。
步骤4:为secretmanager创建一个AWS客户端。
第5步:调用get_secret_value并将secret_stored_location作为SecretId传递。
第6步:检查是纯文本还是加密文本。
步骤7:如果是加密的,调用函数使用base64.b64decode解码二进制值
步骤8:它以解密模式返回所有秘密,即给定位置的纯文本。
第9步:如果在检索值时出现问题,则处理通用异常。
示例代码
使用以下代码从AWSSecretManager获取解密的纯文本密钥-
import boto3 frombotocore.exceptionsimport 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**************"}