What it is
The AWS Serverless Application Model (SAM) Command Line Interface (CLI) is a tool for building, testing, and debugging serverless applications on AWS. You reach for it when you want to develop serverless applications locally before deploying them to AWS.
Installation
Linux
pip install aws-sam-cli
# or using Homebrew
brew install aws-sam-cli
macOS
pip install aws-sam-cli
# or using Homebrew
brew install aws-sam-cli
Windows
Download the appropriate MSI installer from the AWS SAM CLI releases page and run it. Alternatively, use pip:
pip install aws-sam-cli
Core Concepts
- SAM Template: A CloudFormation template written in YAML or JSON that defines your serverless application’s resources, including Lambda functions, API Gateway APIs, DynamoDB tables, and more. SAM provides shorthand syntax for common serverless resources.
- Local Development: SAM CLI allows you to emulate AWS Lambda and API Gateway on your local machine, enabling fast iteration and debugging without deploying to the cloud.
- Build: Compiles your application code and dependencies into a format that can be deployed to AWS Lambda.
- Invoke: Executes your Lambda function locally, simulating an event trigger.
- Start API: Runs a local server that emulates API Gateway, allowing you to test your API endpoints.
- Package: Prepares your SAM template and application code for deployment by uploading code artifacts to S3.
- Deploy: Deploys your serverless application to AWS based on the packaged template.
Commands / Usage
Initializing a Project
-
sam init- Purpose: Initializes a new serverless application project.
- Example:
sam init - Explanation: Prompts you to choose a template (e.g., "Hello World"), runtime (e.g., Python 3.9), and project name.
-
sam init --runtime python3.9 --app-template hello-world --name my-sam-app- Purpose: Initializes a new serverless application project with specific parameters.
- Example:
sam init --runtime python3.9 --app-template hello-world --name my-sam-app - Explanation: Creates a project named
my-sam-appusing thehello-worldtemplate with Python 3.9 runtime.
-
sam init --location aws-samples/cookiecutter-aws-sam-python- Purpose: Initializes a project from a custom SAM template location (e.g., a GitHub repository).
- Example:
sam init --location aws-samples/cookiecutter-aws-sam-python - Explanation: Initializes a project using the cookiecutter template from the specified GitHub repository.
Building Your Application
-
sam build- Purpose: Builds your application, compiling code and installing dependencies.
- Example:
sam build - Explanation: Reads your
template.yamland builds all Lambda functions defined in it.
-
sam build --use-container- Purpose: Builds your application inside a Docker container, ensuring consistency with the Lambda execution environment.
- Example:
sam build --use-container - Explanation: Useful for runtimes that require compilation or have system dependencies, or to ensure your build environment matches the AWS Lambda environment.
-
sam build --template smaller-template.yaml- Purpose: Builds only the resources defined in a specific template file.
- Example:
sam build --template smaller-template.yaml - Explanation: Builds resources defined in
smaller-template.yamlinstead of the defaulttemplate.yaml.
-
sam build --beta-features- Purpose: Enables experimental features during the build process.
- Example:
sam build --beta-features - Explanation: Activates any features marked as beta in the SAM CLI.
Local Testing and Debugging
-
sam local invoke <FunctionName>- Purpose: Invokes a specific Lambda function locally.
- Example:
sam local invoke HelloWorldFunction - Explanation: Executes the Lambda function named
HelloWorldFunctionlocally with no event payload.
-
sam local invoke HelloWorldFunction --event events/event.json- Purpose: Invokes a Lambda function locally with a specific event payload.
- Example:
sam local invoke HelloWorldFunction --event events/event.json - Explanation: Executes
HelloWorldFunctionlocally, passing the contents ofevents/event.jsonas the event.
-
sam local invoke HelloWorldFunction --template-file my-template.yaml- Purpose: Invokes a Lambda function locally using a different SAM template.
- Example:
sam local invoke HelloWorldFunction --template-file my-template.yaml - Explanation: Invokes
HelloWorldFunctionbased on the resource definitions inmy-template.yaml.
-
sam local invoke HelloWorldFunction --debug-port 5858- Purpose: Invokes a Lambda function locally and starts a debugger listening on the specified port.
- Example:
sam local invoke HelloWorldFunction --debug-port 5858 - Explanation: Runs
HelloWorldFunctionand pauses execution, allowing you to attach a debugger (e.g., from VS Code) to port 5858.
-
sam local start-api- Purpose: Starts a local server that emulates API Gateway.
- Example:
sam local start-api - Explanation: Runs a local API Gateway endpoint, typically at
http://127.0.0.1:3000, serving your API defined intemplate.yaml.
-
sam local start-api --template smaller-template.yaml --port 3001- Purpose: Starts a local API Gateway emulator using a specific template and port.
- Example:
sam local start-api --template smaller-template.yaml --port 3001 - Explanation: Starts the API emulator on port 3001, using resources defined in
smaller-template.yaml.
-
sam local start-api --debug- Purpose: Starts the local API Gateway emulator with debugging enabled for all functions.
- Example:
sam local start-api --debug - Explanation: Enables debugging for all functions served by the local API. You can then invoke endpoints and attach a debugger.
-
sam local start-api --debug-port 5858- Purpose: Starts the local API Gateway emulator with a specific debug port for all functions.
- Example:
sam local start-api --debug-port 5858 - Explanation: Allows you to attach a debugger to any Lambda function invoked through the local API on port 5858.
Packaging for Deployment
-
sam package --output-template-file packaged-template.yaml- Purpose: Prepares your SAM application for deployment by uploading code artifacts to S3 and creating a deployable template.
- Example:
sam package --output-template-file packaged-template.yaml - Explanation: Packages your application code, uploads it to an S3 bucket (requires
--s3-bucketorAWS_SAM_CLI_S3_BUCKETenvironment variable), and generatespackaged-template.yamlwith S3 URIs for code.
-
sam package --template-file template.yaml --s3-bucket my-deployment-bucket --output-template-file packaged.yaml- Purpose: Packages your application, specifying the S3 bucket for artifacts and the output template file.
- Example:
sam package --template-file template.yaml --s3-bucket my-deployment-bucket --output-template-file packaged.yaml - Explanation: Uploads code to
my-deployment-bucketand createspackaged.yaml.
-
sam package --use-json- Purpose: Outputs the packaged template in JSON format instead of YAML.
- Example:
sam package --use-json --output-template-file packaged.json - Explanation: Generates
packaged.jsonwith the CloudFormation resources.
Deploying Your Application
-
sam deploy --guided- Purpose: Deploys your SAM application to AWS, prompting you for configuration.
- Example:
sam deploy --guided - Explanation: Guides you through the deployment process, asking for stack name, region, S3 bucket, and confirmation. Creates a
samconfig.tomlfile for future deployments.
-
sam deploy --stack-name my-serverless-app --s3-bucket my-deployment-bucket --capabilities CAPABILITY_IAM- Purpose: Deploys your SAM application to AWS without interactive prompts.
- Example:
sam deploy --stack-name my-serverless-app --s3-bucket my-deployment-bucket --capabilities CAPABILITY_IAM - Explanation: Deploys the application as a CloudFormation stack named
my-serverless-app, usingmy-deployment-bucketfor artifacts, and acknowledges IAM capabilities.
-
sam deploy --template-file packaged.yaml --stack-name my-prod-app --region us-east-1 --parameter-overrides ParameterKey=Stage,ParameterValue=Prod- Purpose: Deploys a pre-packaged template with specific stack name, region, and parameter overrides.
- Example:
sam deploy --template-file packaged.yaml --stack-name my-prod-app --region us-east-1 --parameter-overrides ParameterKey=Stage,ParameterValue=Prod - Explanation: Deploys the
packaged.yamltemplate to theus-east-1region, creating a stack namedmy-prod-app, and sets theStageparameter toProd.
-
sam deploy --config-env dev- Purpose: Deploys using configuration from a specific environment section in
samconfig.toml. - Example:
sam deploy --config-env dev - Explanation: Uses the settings defined under
[deploy.dev]in yoursamconfig.tomlfile.
- Purpose: Deploys using configuration from a specific environment section in
Other Useful Commands
-
sam logs --stack-name my-serverless-app- Purpose: Retrieves logs from Lambda functions in your deployed stack.
- Example:
sam logs --stack-name my-serverless-app - Explanation: Fetches logs for all functions associated with the
my-serverless-appCloudFormation stack.
-
sam logs --stack-name my-serverless-app --name HelloWorldFunction- Purpose: Retrieves logs for a specific Lambda function.
- Example:
sam logs --stack-name my-serverless-app --name HelloWorldFunction - Explanation: Fetches logs only for the
HelloWorldFunctionwithin themy-serverless-appstack.
-
sam logs --stack-name my-serverless-app --tail- Purpose: Tails logs from Lambda functions in real-time.
- Example:
sam logs --stack-name my-serverless-app --tail - Explanation: Continuously streams logs from all functions in the stack.
-
sam validate- Purpose: Validates your SAM template against the SAM schema.
- Example:
sam validate - Explanation: Checks
template.yamlfor syntax errors and adherence to the SAM specification.
-
sam validate --template-file my-template.yaml- Purpose: Validates a specific SAM template file.
- Example:
sam validate --template-file my-template.yaml - Explanation: Validates
my-template.yaml.
-
sam delete --stack-name my-serverless-app- Purpose: Deletes a deployed SAM application’s CloudFormation stack.
- Example:
sam delete --stack-name my-serverless-app - Explanation: Removes the CloudFormation stack named
my-serverless-app.
Common Patterns
Local Development Workflow
- Initialize:
sam init --runtime python3.9 --app-template hello-world --name my-api cd my-api - Build:
sam build --use-container - Start Local API:
sam local start-api --debug-port 5858 - Invoke and Debug:
- Open a new terminal.
- Attach your debugger (e.g., VS Code) to
localhost:5858. - Make an HTTP request to your local API (e.g.,
curl http://127.0.0.1:3000/hello). - If you need to test a specific function with an event:
sam local invoke HelloWorldFunction --event events/event.json --debug-port 5858
Deploying to Staging and Production
Use samconfig.toml to manage different deployment environments.
samconfig.toml:
version = 0.1
[default]
[default.deploy]
[default.deploy.parameters]
stack_name = "my-serverless-app-prod"
s3_bucket = "my-prod-deployment-bucket"
region = "us-east-1"
capabilities = "CAPABILITY_IAM"
[dev]
[dev.deploy]
[dev.deploy.parameters]
stack_name = "my-serverless-app-dev"
s3_bucket = "my-dev-deployment-bucket"
region = "us-east-1"
parameter_overrides = "Stage=Dev"
Deploy to Dev:
sam build --use-container
sam deploy --config-env dev
Deploy to Prod:
sam build --use-container
sam deploy
Retrieving Logs After Deployment
sam logs --stack-name my-serverless-app --name MyLambdaFunction --tail
Validating and Packaging before Deploy
sam validate
sam build --use-container
sam package --s3-bucket my-deployment-bucket --output-template-file packaged.yaml
sam deploy --template-file packaged.yaml --stack-name my-serverless-app --capabilities CAPABILITY_IAM
Gotchas
- Container Dependencies: When using
sam build --use-container, ensure Docker is installed and running. The container image used is specific to the runtime and is downloaded automatically. - S3 Bucket for Packaging: The
sam packagecommand requires an S3 bucket to upload your code artifacts. This bucket must exist in your AWS account and region before you runsam package. You can specify it via--s3-bucketor by setting theAWS_SAM_CLI_S3_BUCKETenvironment variable. - IAM Capabilities: When deploying resources that create IAM roles (like Lambda functions), you must explicitly acknowledge this by including
--capabilities CAPABILITY_IAM(orCAPABILITY_NAMED_IAMorCAPABILITY_AUTO_EXPAND) duringsam deploy. - Local Environment Differences: While
sam localemulates Lambda and API Gateway, it’s not a perfect replica. Some AWS services or specific event structures might behave slightly differently locally than in the actual AWS environment. Always test critical functionality in AWS. - Port Conflicts: If
sam local start-apifails to start, the default port (3000) might already be in use. Use the--portflag to specify an alternative port. - Dependency Management: For Python, SAM CLI typically uses
pip install -r requirements.txtwithin the build process. Ensure yourrequirements.txtis correctly populated. For Node.js, it usesnpm installoryarn install. samconfig.tomlLocation: Thesamconfig.tomlfile should be in the root directory of your SAM project (wheretemplate.yamlresides) forsam deploy --config-envto work correctly.- Build Artifacts Location: The
sam buildcommand places built artifacts in a.aws-sam/builddirectory by default.sam packagethen reads from this directory.