AWS SAM CLI

AWS SAM CLI cheatsheet — build, test, and deploy serverless apps. sam build, sam local invoke, sam local start-api, sam deploy. Test Lambda functions locally before pushing.

10 min read

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-app using the hello-world template 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.yaml and 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.yaml instead of the default template.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 HelloWorldFunction locally 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 HelloWorldFunction locally, passing the contents of events/event.json as 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 HelloWorldFunction based on the resource definitions in my-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 HelloWorldFunction and 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 in template.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-bucket or AWS_SAM_CLI_S3_BUCKET environment variable), and generates packaged-template.yaml with 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-bucket and creates packaged.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.json with 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.toml file 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, using my-deployment-bucket for 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.yaml template to the us-east-1 region, creating a stack named my-prod-app, and sets the Stage parameter to Prod.
  • 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 your samconfig.toml file.

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-app CloudFormation 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 HelloWorldFunction within the my-serverless-app stack.
  • 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.yaml for 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

  1. Initialize:
    sam init --runtime python3.9 --app-template hello-world --name my-api
    cd my-api
    
  2. Build:
    sam build --use-container
    
  3. Start Local API:
    sam local start-api --debug-port 5858
    
  4. 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 package command requires an S3 bucket to upload your code artifacts. This bucket must exist in your AWS account and region before you run sam package. You can specify it via --s3-bucket or by setting the AWS_SAM_CLI_S3_BUCKET environment variable.
  • IAM Capabilities: When deploying resources that create IAM roles (like Lambda functions), you must explicitly acknowledge this by including --capabilities CAPABILITY_IAM (or CAPABILITY_NAMED_IAM or CAPABILITY_AUTO_EXPAND) during sam deploy.
  • Local Environment Differences: While sam local emulates 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-api fails to start, the default port (3000) might already be in use. Use the --port flag to specify an alternative port.
  • Dependency Management: For Python, SAM CLI typically uses pip install -r requirements.txt within the build process. Ensure your requirements.txt is correctly populated. For Node.js, it uses npm install or yarn install.
  • samconfig.toml Location: The samconfig.toml file should be in the root directory of your SAM project (where template.yaml resides) for sam deploy --config-env to work correctly.
  • Build Artifacts Location: The sam build command places built artifacts in a .aws-sam/build directory by default. sam package then reads from this directory.