DEV Community

Cover image for How to retrieve DynamoDB items using secrets stored in AWS Secrets Manager with AWS Lambda - 2

How to retrieve DynamoDB items using secrets stored in AWS Secrets Manager with AWS Lambda - 2

Please read my previous article - How to retrieve DynamoDB items using secrets stored in AWS Secrets Manager with AWS Lambda - 1

Let’s get started!

Please visit my GitHub Repository for DynamoDB articles on various topics being updated on constant basis.

Pre-requisites:

  • AWS user account with admin access, not a root account.
  • Create an IAM role

Resources Used:

What is Amazon DynamoDB?

What is AWS Secrets Manager?

What is AWS Lambda?

Steps for implementation to this project:

Part 2

6. Create a Secret Manager to Store Access key and Secret Access keys

1

Image description

2

Image description

3

Image description

4

Image description

  • Next
  • Next
  • Store

5

Image description

6

Image description

7. Write a Lambda code to create DynamoDB Items by retrieving the access keys from Secrets Manager.

1

  • Click on Functions at the left side and select the Function you created.

  • Select the Code tab under the lambda myFunction

  • Copy the file3, replace it with the existing code and and change the Secret ARN in file3

import boto3
import json
import base64

def lambda_handler(event, context):
    secret_name = "arn:aws:secretsmanager:us-east-1:xxxxxxxxxxxx:secret:mySecret-q7slUY"
    # Create a Secrets Manager client
    secretClient = boto3.client(
        service_name = 'secretsmanager',
        region_name = 'us-east-1'
    )

    get_secret_value_response = secretClient.get_secret_value(
        SecretId=secret_name
    )
    secret = get_secret_value_response['SecretString']
    Table_name = 'myTable2'

    print('DynamoDB Table creation started.')

    dynamodb = boto3.resource(
        'dynamodb',
        aws_access_key_id = json.loads(secret).get('Access Key'),
        aws_secret_access_key = json.loads(secret).get('Secret Access Key'),
        region_name = 'us-east-1'
    )

    student_table = dynamodb.create_table(
        TableName = Table_name,
        KeySchema = [
            {
                'KeyType': 'HASH',
                'AttributeName': 'StudId'
            }
        ],
        AttributeDefinitions=[
            {
                'AttributeName': 'StudId',
                'AttributeType': 'N'
            }
        ],
        ProvisionedThroughput={
            'ReadCapacityUnits': 2,
            'WriteCapacityUnits': 2
        }
    )

    # Wait until the Table gets created
    student_table.meta.client.get_waiter('table_exists').wait(TableName = Table_name)
    print('DynamoDB Table Creation Completed.')

    print('Insert Student data to table started.')
    # Insert 1st item into DynamoDB table
    table = dynamodb.Table(Table_name)
    table.put_item(
    Item = {
            'StudId': 100,
            'FirstName': 'Rev1',
            'LastName': 'Joshi1',
            'Dept': 'Science',
            'Age': 11
        }
    )



    # Insert 2nd item into DynamoDB table
    table.put_item(
    Item = {
            'StudId': 200,
            'FirstName': 'Rev2',
            'LastName': 'Joshi2',
            'Dept': 'Science',
            'Age': 22
        }
    )



    # Insert 3rd item into DynamoDB table
    table.put_item(
    Item = {
            'StudId': 300,
            'FirstName': 'Rev3',
            'LastName': 'Joshi3',
            'Dept': 'Science',
            'Age': 33
        }
    )
    print('Insert Student data to table Completed.')
Enter fullscreen mode Exit fullscreen mode

Image description

  • Deploy
  • Test
  • Output

2

Image description

8. View DynamoDB Table created in console.

1

Image description

2

  • Select the table myTable2 and click on Explore table items Button in the right side

Image description

9. Write a lambda code to view the table items using a secret manager.

1

  • Click on Functions at the left side and select the Function you created.

  • Select the Code tab under the lambda myFunction

  • Copy the file4, replace it with the existing code and change the Secret ARN in file4

import boto3
import json
import base64

def lambda_handler(event, context):
    secret_name = "arn:aws:secretsmanager:us-east-1:xxxxxxxxxxxx:secret:mySecret-q7slUY"
    # Create a Secrets Manager client
    secretClient = boto3.client(
        service_name = 'secretsmanager',
        region_name = 'us-east-1'
    )

    get_secret_value_response = secretClient.get_secret_value(
        SecretId=secret_name
    )

    secret = get_secret_value_response['SecretString']
    Table_name = 'myTable2'

    # Create a DynamoDB table
    print('DynamoDB Table creation started.')

    dynamodb = boto3.resource(
        'dynamodb',
        aws_access_key_id = json.loads(secret).get('Access Key'),
        aws_secret_access_key = json.loads(secret).get('Secret Access Key'),
        region_name = 'us-east-1'
    )

    # Connect to table & Scan the entire table
    table = dynamodb.Table(Table_name)
    response = table.scan()

    print('---------------------------------------')
    print('------------STUDENT DETAILS------------')
    print('---------------------------------------')
    for item in response['Items']:
        print('Student Id : ', item['StudId'])
        print('Student Name : ', item['FirstName'], ' ', item['LastName'])
        print('Student Department : ', item['Dept'])
        print('Student Age : ', item['Age'])
        print('_______________________________')
    print('---------------------------------------')

Enter fullscreen mode Exit fullscreen mode
  • Deploy
  • Test
  • Output

Image description

Cleanup

  • Delete Lambda Function
  • Delete DynamoDB tables
  • Delete Secrets

What we have done so far

  • Successfully retrieved items from DynamoDB tables using secrets stored in AWS Secrets Manager with AWS Lambda function.

Top comments (0)