Connect a Serverless AWS SAM application to DynamoDB

written by Guido Percú on June 7, 2020

sam-logo

SAM Template for minimal application using DynamoDB

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
  ProcessDynamoDBStream:
    Type: AWS::Serverless::Function
    Properties:
      Handler: handler
      Runtime: runtime
      Policies: AWSLambdaDynamoDBExecutionRole
      Events:
        Stream:
          Type: DynamoDB
          Properties:
            Stream: !GetAtt DynamoDBTable.StreamArn
            BatchSize: 100
            StartingPosition: TRIM_HORIZON

  DynamoDBTable:
    Type: AWS::DynamoDB::Table
    Properties: 
      AttributeDefinitions: 
        - AttributeName: id
          AttributeType: S
      KeySchema: 
        - AttributeName: id
          KeyType: HASH

Validate the template file

sam validate will take a look at your template.yaml file and see if it looks correct. This command is very useful because it checks for removed references and wrong indentation.

Build and deploy

To deploy, let's first build it using sam build --use-container This will build the source of your application and prepare it to run locally (with sam local invoke) or to ship it to AWS.

Then it's time to package and deploy your application to AWS, with a series of prompts:

sam deploy --guided

  • Stack Name: The name of the stack to deploy to CloudFormation. This should be your project name.
  • AWS Region: The AWS region you want to deploy your app to.
  • Confirm changes before deploy: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes.
  • Allow SAM CLI IAM role creation: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions.
  • Save arguments to samconfig.toml: In the future you can just re-run sam deploy without parameters to deploy changes to your application, because your choices will be saved in a samconfig.toml file.

Have fun!