How to retrieve DynamoDB items using secrets stored in AWS Secrets Manager with AWS Lambda - 2
Tags: dynamodb, secretsmanager, lambda, accesskeys
Published: 2024-03-13 21:05:51

Please read my previous article - **[How to retrieve DynamoDB items using secrets stored in AWS Secrets Manager with AWS Lambda - 1](https://dev.to/aws-builders/how-to-retrieve-dynamodb-items-using-secrets-stored-in-aws-secrets-manager-with-aws-lambda-1-4n6b)**

_**Let’s get started!**_


Please visit my **[GitHub Repository for DynamoDB articles](https://github.com/awsmine/DynamoDB_projects)** 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?](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html)**

**[What is AWS Secrets Manager?](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html)**

**[What is AWS Lambda?](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)**

# Steps for implementation to this project:

## Part 2

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

**1**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jgvllvq6v8uks4eqpmhy.png)

**2**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xhqmd8qywzsoqrk7j8el.png)

**3**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/645ddtp5rfmq70navhj1.png)

**4**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1r2n25axejcioil2l3xt.png)

- Next
- Next
- Store

**5**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qrv21g9dimpn5qruguzi.png)

**6**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dikfxm5jqb6zirdih3f0.png)


## 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.')
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m8cxlpn56mfsrdzhu53p.png)

- Deploy
- Test
- Output

**2**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kwd19mt00hbpkncdntn0.png)

## 8. View DynamoDB Table created in console.

**1**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zjlu3xrg35w2mj1mcbyl.png)

**2**

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bxo83ynu5fsqk1bdviyg.png)

## 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('---------------------------------------')

```

- Deploy
- Test
- Output

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tinauh5h1wqbx1b8zuuv.png)


# 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.