Getting started with Amazon SAM and the Amazon CDK
This topic describes what you need to use the Amazon SAM CLI with Amazon CDK applications, and provides instructions for building and locally testing a simple Amazon CDK application.
Prerequisites
To use the Amazon SAM CLI with Amazon CDK, you must install the Amazon CDK, and the Amazon SAM CLI.
-
For information about installing the Amazon CDK, see Getting started with the Amazon CDK in the Amazon Cloud Development Kit (Amazon CDK) Developer Guide.
-
For information about installing the Amazon SAM CLI, see Installing the Amazon SAM CLI.
Creating and locally testing an Amazon CDK application
To locally test an Amazon CDK application using the Amazon SAM CLI, you must have an Amazon CDK application that contains a Lambda function. Use the following steps to create a basic Amazon CDK application with a Lambda function. For more information, see Creating a serverless application using the Amazon CDK in the Amazon Cloud Development Kit (Amazon CDK) Developer Guide.
Note
The Amazon SAM CLI supports Amazon CDK v1 starting from version 1.135.0 and Amazon CDK v2 starting from version 2.0.0.
Step 1: Create an Amazon CDK application
For this tutorial, initialize an Amazon CDK application that uses TypeScript.
Command to run:
Step 2: Add a Lambda function to your application
Replace the code in lib/cdk-sam-example-stack.ts
with the following:
Step 3: Add your Lambda function code
Create a directory named my_function
. In that directory, create a file named app.py
.
Command to run:
mkdir my_function cd my_function touch app.py
Add the following code to app.py
:
def lambda_handler(event, context): return "Hello from SAM and the CDK!"
Step 4: Test your Lambda function
You can use the Amazon SAM CLI to locally invoke a Lambda function that you define in an Amazon CDK application. To do this, you need the function construct identifier and the path to your synthesized Amazon CloudFormation template.
Command to run:
cdk synth --no-staging
sam local invoke
MyFunction
--no-event -t./cdk.out/CdkSamExampleStack.template.json
Example output:
Invoking app.lambda_handler (python3.9) START RequestId: 5434c093-7182-4012-9b06-635011cac4f2 Version: $LATEST "Hello from SAM and the CDK!" END RequestId: 5434c093-7182-4012-9b06-635011cac4f2 REPORT RequestId: 5434c093-7182-4012-9b06-635011cac4f2 Init Duration: 0.32 ms Duration: 177.47 ms Billed Duration: 178 ms Memory Size: 128 MB Max Memory Used: 128 MB
For more information about options available to test Amazon CDK applications using the Amazon SAM CLI, see Locally testing Amazon CDK applications.