How do I connect to DynamoDB from a Lambda instance in a VPC?
I want to integrate Amazon DynamoDB with my AWS Lambda instance in an Amazon Virtual Private Cloud (Amazon VPC).
Resolution
Prerequisites:
- Create a DynamoDB table. Then, write data to the table.
- Create an Amazon VPC.
- Create a gateway endpoint for DynamoDB. For VPC, choose your Amazon VPC.
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:
Note: Replace TableName and Key with your values.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!') }
- 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
Contenuto pertinente
- AWS UFFICIALEAggiornata 2 anni fa
- AWS UFFICIALEAggiornata 6 mesi fa
- AWS UFFICIALEAggiornata un anno fa
- AWS UFFICIALEAggiornata un anno fa