Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Testing a Lambda function locally against DynamoDB on AWS.

Local development with SAM

This method allows you to iterate very quickly against Lambda code without having to run AWS resources locally.

Requirements

Step 1: Create and deploy a simple SAM Template (see template.yaml)

  • must include the environment varibales on the Lambda to pass the SAMPLE_TABLE in (see line 17)
  • use sam deploy --guided for the first time deploy

Ths will create the table in the AWS dev account and will be accessible to the locally invoked Lambda function via the AWS CLI credentials

Step 2: Create a local environments file (See locals.json)

  • Ensure it contains the name of the actual table created in the deploy
  • I also have an "experimental" python script that will build this for you. (see build-params.py)

Step 3: Test locally

  • requires an AWS CLI profile to be configured with CRUD access to dynamodb

A single invoke

sam local invoke getAllItemsFunction -n locals.json

As a listening API Gateway emulator

sam local start-api -n locals.js

More Info

https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-using-invoke.html

# Use at your own risk.
# Set path/to/python
# requires boto3
# requires an AWS CLI profile to be configured
#!/path/to/python
import sys, json
import boto3
if len(sys.argv) == 1:
print('CloudFormation stack required')
sys.exit()
cloudformation_client = boto3.client('cloudformation')
lambda_client = boto3.client('lambda')
page = {}
# Grab stack from AWS
try:
stack_resources = cloudformation_client.list_stack_resources(
StackName=sys.argv[1]
)
except Exception as e:
print(e)
sys.exit()
# Grab environment vars from each lambda in the stack
for resource in stack_resources['StackResourceSummaries']:
if(resource['ResourceType']=='AWS::Lambda::Function'):
lambda_config = lambda_client.get_function_configuration(
FunctionName=resource['PhysicalResourceId']
)
if 'Environment' in lambda_config and 'Variables' in lambda_config['Environment']:
page[resource['LogicalResourceId']] = lambda_config['Environment']['Variables']
# Print to console
print(json.dumps(page, indent=2))
{
"getAllItemsFunction": {
"SAMPLE_TABLE": "SampleTable-3MNBRQBENB1F"
}
}
AWSTemplateFormatVersion: 2010-09-09
Description: My App
Transform: AWS::Serverless-2016-10-31
Resources:
getAllItemsFunction:
Type: AWS::Serverless::Function
Properties:
Handler: src/handlers/get-all-items.getAllItemsHandler
Runtime: nodejs10.x
MemorySize: 128
Timeout: 100
Description: A simple example includes a HTTP get method to get all items from a DynamoDB table.
Policies:
- DynamoDBCrudPolicy:
TableName: !Ref SampleTable
Environment:
Variables:
SAMPLE_TABLE: !Ref SampleTable
Events:
Api:
Type: Api
Properties:
Path: /
Method: GET
# DynamoDB table to store item:
SampleTable:
Type: AWS::Serverless::SimpleTable
Outputs:
WebEndpoint:
Description: "API Gateway endpoint URL for Prod stage"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment