I want to integrate Amazon DynamoDB with my AWS Lambda instance in an Amazon Virtual Private Cloud (Amazon VPC).
Resolution
Prerequisites:
Connect Lambda to DynamoDB
Complete the following steps:
- Open the Lambda console.
- In the navigation pane, choose Functions.
- Choose Create function.
- Choose Author from scratch.
- For Basic information, configure the following:
For Function name, enter a name for your function.
For Runtime, choose a runtime option. In this example, Python 3.12 is used.
For Architecture, choose x86_64.
- Under Advanced settings, configure the following:
Select Enable VPC, and then select your VPC.
For Subnets, select only private subnets.
For Security groups, select the default security group.
- Choose Create function.
- On the Function details page, under Code source, enter the following code:
import json
import boto3
client = boto3.client('dynamodb')
def lambda_handler(event, context):
response = client.get_item(
TableName='Music',
Key={
'Artist': {
'S': 'No One You Know',
},
'SongTitle': {
'S': 'Call Me Today',
},
}
)
print(response)
return {
'statusCode': 200,
'body': json.dumps('Success!')
}
Note: Replace TableName and Key with your values.
- Choose Deploy.
- Test your function.
Note: To test the function, the AWS Identity and Access Management (IAM) role for Lambda must have the appropriate permissions. For more information, see Managing permissions in AWS Lambda.
Additional troubleshooting
To troubleshoot a Lambda function that's attached to a VPC, take the following actions:
-
Remove any connections to public subnets from your Lambda function. If you connect to public subnets, then traffic tries to pass through the public subnets and can cause intermittent timeout issues.
-
Make sure that your gateway endpoint for DynamoDB is correctly configured.
-
Update your private subnets that are associated with your Lambda function to route through your DynamoDB VPC gateway endpoint. These endpoints have AWS managed prefix lists that simplify the configuration of security group settings between Lambda and DynamoDB.
Example private subnet route table:
Route Table: rtb-12345
Destination Gateway Status
10.0.0.0/16 local active
pl-1234 vpce-1234 active
-
Update your Lambda security group rules to allow all traffic.
Related information
Create a Lambda function with the console
Using Amazon VPC endpoints to access DynamoDB
Networking and VPC configurations