In this demo, we will:
admin
MySecurePassword123!
demo/db/credentials
SecretsManagerDemo
import json
import boto3
from botocore.exceptions import ClientError
def get_secret():
secret_name = "demo/db/credentials"
region_name = "us-east-1"
# Create a Secrets Manager client
session = boto3.session.Session()
client = session.client(
service_name='secretsmanager',
region_name=region_name
)
try:
get_secret_value_response = client.get_secret_value(
SecretId=secret_name
)
except ClientError as e:
# For a list of exceptions thrown, see
# https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
raise e
# Decrypts secret using the associated KMS key.
secret = get_secret_value_response['SecretString']
# Parse the JSON string into a Python dictionary
return json.loads(secret)
def lambda_handler(event, context):
try:
secret_dict = get_secret()
# Print the entire secret structure for debugging
print(f"Secret structure: {json.dumps(secret_dict)}")
# In this case, the username is the key and the password is the value
username = list(secret_dict.keys())[0]
password = secret_dict[username]
return {
'statusCode': 200,
'body': json.dumps(f"Successfully retrieved secret. Username: {username}, Password: {password}")
}
except Exception as e:
print(f"Error: {str(e)}")
return {
'statusCode': 500,
'body': json.dumps(f"Error retrieving secret: {str(e)}")
}
Copy Paste the Secrets Manager Secret's ARN
SecretsManagerDemoPolicy