AWS Secrets Manager

Hands-On

Demo

Agenda

In this demo, we will:

  1. Create a secret in AWS Secrets Manager
  2. Retrieve and use the secret
  3. Create a Lambda function to access the secret
  4. Test the Lambda function
  5. Clean up resources

Demo Overview

Choose secret type

admin
MySecurePassword123!

Secret name and description

demo/db/credentials

Review

Secret configuration

Rotation schedule

Secrets List

Retrieve and view the secret value.

Create Lambda function

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)}")
        }

Edit Execution role

SecretsManagerDemo-role

Manually Create Inline Policy

Copy Paste the Secrets Manager Secret's ARN

SecretsManagerDemoPolicy

Review and create

Test the Lambda Function

Execution Result 

Clean Up

Delete secret

Delete function

Delete Lambda Execution Role

🙏

Thanks

for

Watching

AWS Secrets Manager - Hands-On Demo

By Deepak Dubey

AWS Secrets Manager - Hands-On Demo

AWS Secrets Manager - Hands-On Demo

  • 135