AWS SAM CDK locally

Running AWS CDK applications with SAM locally

published: Tue, 27 Dec 2022 estimated reading time: 1 minute

In this post we will make an AWS lambda function with python and CDK and run it locally with AWS SAM.

Prerequisite

Create lambda function with CDK

Create an empty directory and initialize a CDK template.

mkdir cdk-sam-lambda
cd cdk-sam-lambda
cdk init app --language python

Activate the virtualenv, upgrade pip and install the dependencies.

source .venv/bin/activate
pip install --upgrade pip
pip install -r requirements.txt
pip install -r requirements-dev.txt

In cdk_sam_lambda_stack.py add the following code to get a basic lambda function.

1
2
3
4
5
6
7
from aws_cdk import aws_lambda as _lambda

_lambda.Function(self, "MyFunction",
                         runtime=_lambda.Runtime.PYTHON_3_9,
                         handler="app.lambda_handler",
                         code=_lambda.Code.from_asset("./my_code")
                         )

Create my_code directory with an app.py file.

mkdir my_code
cd my_code
touch app.py

Add the following code to app.py.

1
2
3
4
def lambda_handler(event, context):
    print(event)
    print(context)
    return "Hello from SAM and the CDK!"

Run lambda locally with SAM

Generate the cloudformation from CDK.

cdk synth --no-staging

Generate a test even with SAM.

sam local generate-event apigateway aws-proxy > apigateway_testevent.json

Run the lambda locally with the generated event.

sam local invoke MyFunction ./apigateway_testevent.json -t ./cdk.out/CdkSamLambdaStack.template.json

The output should look something like this.

img.png