将AWS机密管理器与Python结合使用(Lambda控制台)
我试图在AWS中使用Secrets Manager的Lambda函数。机密管理器用于将数据库凭据存储到Snowflake(用户名、密码) 我设法在Secrets Manager中设置了一个secret,其中包含多个密钥/值对(例如,一个用于用户名,另一个用于密码) 现在我试图在Python函数代码中引用这些值。AWS文档提供了以下代码片段:将AWS机密管理器与Python结合使用(Lambda控制台),python,amazon-web-services,aws-lambda,aws-secrets-manager,Python,Amazon Web Services,Aws Lambda,Aws Secrets Manager,我试图在AWS中使用Secrets Manager的Lambda函数。机密管理器用于将数据库凭据存储到Snowflake(用户名、密码) 我设法在Secrets Manager中设置了一个secret,其中包含多个密钥/值对(例如,一个用于用户名,另一个用于密码) 现在我试图在Python函数代码中引用这些值。AWS文档提供了以下代码片段: import boto3 import base64 from botocore.exceptions import ClientError def g
import boto3
import base64
from botocore.exceptions import ClientError
def get_secret():
secret_name = "MY/SECRET/NAME"
region_name = "us-west-2"
# Create a Secrets Manager client
session = boto3.session.Session()
client = session.client(
service_name='secretsmanager',
region_name=region_name
)
# In this sample we only handle the specific exceptions for the 'GetSecretValue' API.
# See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
# We rethrow the exception by default.
try:
get_secret_value_response = client.get_secret_value(
SecretId=secret_name
)
except ClientError as e:
if e.response['Error']['Code'] == 'DecryptionFailureException':
# Secrets Manager can't decrypt the protected secret text using the provided KMS key.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
elif e.response['Error']['Code'] == 'InternalServiceErrorException':
# An error occurred on the server side.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
elif e.response['Error']['Code'] == 'InvalidParameterException':
# You provided an invalid value for a parameter.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
elif e.response['Error']['Code'] == 'InvalidRequestException':
# You provided a parameter value that is not valid for the current state of the resource.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
elif e.response['Error']['Code'] == 'ResourceNotFoundException':
# We can't find the resource that you asked for.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
else:
# Decrypts secret using the associated KMS CMK.
# Depending on whether the secret is a string or binary, one of these fields will be populated.
if 'SecretString' in get_secret_value_response:
secret = get_secret_value_response['SecretString']
else:
decoded_binary_secret = base64.b64decode(get_secret_value_response['SecretBinary'])
# Your code goes here.
稍后在我的def lambda_handler(event,context)
函数中,我有以下代码片段来建立与数据库的连接:
conn = snowflake.connector.connect(
user=USERNAME,
password=PASSWORD,
account=ACCOUNT,
warehouse=WAREHOUSE,
role=ROLE
)
但是,我不知道如何使用get_secret()
函数返回参数值,如USERNAME
或PASSWORD
如何做到这一点?谢谢你的帮助 - 下面是我如何使用arn使用它的,希望对您有所帮助李>
- 值得检查您用来存储和相应使用的内容
或SecretString
SecretBinary
- 从指定版本的机密中检索加密字段
或SecretString
的内容,以包含内容的为准SecretBinary
- 根据使用的内容,您的lambda角色应具有以下权限
secretsmanager:GetSecretValue
kms:仅当您使用客户管理的AWS kms密钥加密机密时,才需要解密。使用帐户的默认AWS managed CMK for Secrets Manager不需要此权限
pysecret
创建一个从pysecret导入AWSSecret
aws\u profile=“我的aws\u profile”
aws=AWSSecret(配置文件名称=aws\U配置文件)
机密\u id=“我的示例机密”
机密数据={
“主机”:“www.example.com”,
“端口”:1234,
“数据库”:“mydatabase”,
“用户名”:“管理员”,
“密码”:“我的密码”,
“元数据”:{
“创造者”:“爱丽丝”
}
}
aws.deploy_secret(name=secret\u id,secret\u data=secret\u data)#或者,如果您创建了自定义kms密钥,则可以传递kms_key\u id
然后,您应该能够看到在aws控制台中创建的秘密
aws=AWSSecret(profile\u name=aws\u profile)#在lambda代码中,不需要``profile\u name=aws\u profile``
password=aws.get_secret_value(secret_id=“my example secret”,key=“password”)#mypassword
creator=aws.get_secret_值(secret_id=“我的示例secret”,key=“metadata.creator”)#Alice
注意,Lambda函数IAM角色要求访问机密
aws kms create grant
命令授予Lambda函数IAM角色以访问kms密钥进行加密,方法如下如果有此帮助,请启动我的项目。将get_secret()的最后一部分更新为:
这将返回一个字典,其中包含您在AWS Secret Manager控制台中指定的密钥。AWS为一些受支持的数据库引擎(如MySQL等)提供了一些模板,请查看以下内容: 有关不支持的数据库,请检查
上面提供的模板将为您提供一个自定义自己功能的示例。hi@Prashanth kumar您的意思是: def get_secret():
在处理函数中调用函数不起作用?以json的形式返回秘密对我有帮助+1.Thanks@Prashanthkumar您是通过添加
返回值
获得词典的吗?我正在努力获取我的凭据。@django unchained,希望您已经了解了,否则,我只是附上了base64.b64解码(get_secret\u value\u response['SecretBinary'])
insidejson.loads
将其分配给变量“secret”,然后我可以作为secret[“username”]访问凭据
secret[“password”]
,或者secrets manager secret中的任何变量。您可以提供您的代码吗?我陷入这种境地好几天了
secrets_client = boto3.client('secretsmanager')
secret_arn = 'arn:aws:secretsmanager:eu-west-2:xxxxxxxxxxxx:secret:dashboard/auth_token'
auth_token = secrets_client.get_secret_value(SecretId=secret_arn).get('SecretString')
else:
# Decrypts secret using the associated KMS CMK.
# Depending on whether the secret is a string or binary, one of these fields will be populated.
if 'SecretString' in get_secret_value_response:
secret = get_secret_value_response['SecretString']
else:
secret = base64.b64decode(get_secret_value_response['SecretBinary'])
return json.loads(secret) # returns the secret as dictionary
secret_name = "MySecretForRedshift"
region_name = "us-east-1"
# Create a Secrets Manager client
session = boto3.session.Session()
client = session.client(
service_name='secretsmanager',
region_name=region_name
)
# In this sample we only handle the specific exceptions for the 'GetSecretValue' API.
# See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
# We rethrow the exception by default.
try:
get_secret_value_response = client.get_secret_value(
SecretId=secret_name
)
except ClientError as e:
if e.response['Error']['Code'] == 'DecryptionFailureException':
# Secrets Manager can't decrypt the protected secret text using the provided KMS key.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
elif e.response['Error']['Code'] == 'InternalServiceErrorException':
# An error occurred on the server side.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
elif e.response['Error']['Code'] == 'InvalidParameterException':
# You provided an invalid value for a parameter.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
elif e.response['Error']['Code'] == 'InvalidRequestException':
# You provided a parameter value that is not valid for the current state of the resource.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
elif e.response['Error']['Code'] == 'ResourceNotFoundException':
# We can't find the resource that you asked for.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
else:
# Decrypts secret using the associated KMS CMK.
# Depending on whether the secret is a string or binary, one of these fields will be populated.
if 'SecretString' in get_secret_value_response:
secret = json.loads(get_secret_value_response['SecretString'])
else:
secret = json.loads(base64.b64decode(get_secret_value_response['SecretBinary']))
return secret