Trigger the lambda with dynamodb when a specific entry is registered

Viewed 413

I need to trigger a lambda when a specific object registers on DynamoDB.

For example:

If I create a User with a POST /my-website/user and, I store this User on DynamoDB, I want to trigger my Lambda.

I don't want to trigger the Lambda if the registered object is different from the User.

enter image description here

For the management of my stack, I use Serverless (with a serverless.yml file) and CloudFormation syntax.

With the serverless documentation, I can't figure out how I can trigger my Lambda only when a specific entry is registered to DynamoDB ( https://www.serverless.com/framework/docs/providers/aws/events/streams ).

Thanks in advance,

EDIT:

Thank you for your answers :)

It's work:

  statement:
    handler: lambda/statement.php
    layers:
      - arn:aws:lambda:#{AWS::Region}:<account_id>:layer:php-73:1
    iamRoleStatements:
      - Effect: Allow
        Action:
          - dynamodb:ListStreams
          - dynamodb:GetItem
    events:
    - stream:
        type: dynamodb
        arn: arn:aws:dynamodb:eu-west-3:<account_id>:table/dev-project/stream/2020-11-18T22:34:01.579
        maximumRetryAttempts: 1
        batchSize: 1
        filterPatterns:
          - eventName: [INSERT]
            dynamodb:
              NewImage:
                __partitionKey:
                  S: [myPk]
3 Answers

You attach the DynamoDB stream event onto the lambda in your serverless file in the function's "events" sections. https://carova.io/snippets/serverless-aws-dynamodb-stream-to-lamba-function

If you're creating the Dynamo table using serverless, you could output the table's StreamArn as a stack variable. https://carova.io/snippets/serverless-aws-cloudformation-output-stack-variables

If they're in the same file, you don't need the Output section, you could just set the "events" sections of the lambda and reference

arn: { Fn::GetAtt: [DynamoTable, StreamArn] }

in the arn section of the specific event.

Stream Filters worked (thank you). Here's the final configuration:

  statement:
    handler: lambda/statement.php
    layers:
      - arn:aws:lambda:#{AWS::Region}:<account_id>:layer:php-73:1
    iamRoleStatements:
      - Effect: Allow
        Action:
          - dynamodb:ListStreams
          - dynamodb:GetItem
    events:
    - stream:
        type: dynamodb
        arn: arn:aws:dynamodb:eu-west-3:<account_id>:table/dev-project/stream/2020-11-18T22:34:01.579
        maximumRetryAttempts: 1
        batchSize: 1
        filterPatterns:
          - eventName: [INSERT]
            dynamodb:
              NewImage:
                __partitionKey:
                  S: [myPk]
Related