How do I connect to DynamoDB from a Lambda instance in a VPC?

3 分的閱讀內容
2

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:

  1. Open the Lambda console.
  2. In the navigation pane, choose Functions.
  3. Choose Create function.
  4. Choose Author from scratch.
  5. 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.
  6. 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.
  7. Choose Create function.
  8. 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.
  9. Choose Deploy.
  10. 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

AWS 官方
AWS 官方已更新 3 個月前