Lesson 1 of 2 AWS SAM and the AWS CDK

Building Serverless Applications with AWS SAM

The AWS Serverless Application Model (AWS SAM) is an extension of CloudFormation that describes serverless applications with a concise syntax, together with a command line interface that builds, tests and deploys them. This lesson explains the SAM transform and resource types, global settings, policy templates and connectors, event sources, and the SAM CLI workflow from local testing to pipeline deployment.

Learning outcomes

After completing this lesson, you will be able to:

  • Explain how the AWS SAM transform expands SAM resource types into CloudFormation resources.
  • Describe the main SAM resource types, the Globals section, policy templates and connectors.
  • Describe the SAM CLI commands for building, testing locally, syncing and deploying applications.
  • Explain how SAM supports gradual deployments and pipeline generation.

The SAM Transform

A SAM template is a CloudFormation template that declares Transform: AWS::Serverless-2016-10-31. During deployment, CloudFormation runs the SAM transform, which expands each SAM resource into the CloudFormation resources it represents. A single AWS::Serverless::Function with an API event, for example, becomes a Lambda function, an execution role, a Lambda permission, an API Gateway REST API, a deployment and a stage. Because the output is ordinary CloudFormation, SAM templates can contain any CloudFormation resource, and all CloudFormation features, such as change sets, stack policies and rollback triggers, apply. Deploying a SAM template requires CAPABILITY_AUTO_EXPAND as well as the IAM capabilities.

SAM Resource Types

SAM defines a small set of resource types for common serverless components. They are summarised in the table below.

Resource typeCreatesNotes
AWS::Serverless::FunctionA Lambda function, its role and event source integrationsEvents, policies, AutoPublishAlias and DeploymentPreference
AWS::Serverless::ApiAn API Gateway REST APIStages, authorisers, OpenAPI definitions, canary settings
AWS::Serverless::HttpApiAn API Gateway HTTP APILower cost and latency, JWT authorisers
AWS::Serverless::SimpleTableA DynamoDB table with a single-attribute primary keyFor simple tables; use AWS::DynamoDB::Table otherwise
AWS::Serverless::LayerVersionA Lambda layer versionShared libraries
AWS::Serverless::StateMachineA Step Functions state machineDefinition substitutions and policy templates
AWS::Serverless::ApplicationA nested applicationFrom the AWS Serverless Application Repository or a local template
AWS::Serverless::ConnectorIAM permissions between two resourcesGenerates least-privilege policies

The Events property of a function connects event sources in one place: Api and HttpApi for HTTP endpoints, S3, SQS, SNS, DynamoDB and Kinesis streams, Schedule and ScheduleV2 for EventBridge schedules, and EventBridgeRule for event patterns. SAM creates the triggers, event source mappings and permissions.

Globals, Policy Templates and Connectors

The Globals section sets properties shared by all functions or APIs, such as runtime, memory, timeout, tracing, environment variables and architectures, so they are not repeated. Individual resources can override them.

Permissions are a common source of over-privileged serverless applications. SAM policy templates provide scoped policies by name with a parameter, such as DynamoDBCrudPolicy: {TableName: !Ref OrdersTable}, SQSSendMessagePolicy or S3ReadPolicy, each granting only the actions for that resource. Connectors go further: a connector declares that a source resource needs Read or Write access to a destination, and SAM generates the correct IAM policy for that combination of services, which removes the need to know the specific actions.

Transform: AWS::Serverless-2016-10-31
Globals:
  Function:
    Runtime: python3.12
    Architectures: [arm64]
    Timeout: 10
    Tracing: Active
Resources:
  OrdersTable:
    Type: AWS::DynamoDB::Table
    Properties:
      BillingMode: PAY_PER_REQUEST
      AttributeDefinitions: [{AttributeName: pk, AttributeType: S}]
      KeySchema: [{AttributeName: pk, KeyType: HASH}]
  CreateOrder:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/create_order/
      Handler: app.handler
      Environment:
        Variables: {TABLE: !Ref OrdersTable}
      Events:
        Post:
          Type: HttpApi
          Properties: {Path: /orders, Method: post}
    Connectors:
      TableWrite:
        Properties:
          Destination: {Id: OrdersTable}
          Permissions: [Write]

The SAM CLI Workflow

The SAM CLI supports the whole development cycle. Each command is described below in the order a developer typically uses them.

  • sam init creates a project from a template.
  • sam build resolves dependencies and builds each function into .aws-sam/build; --use-container builds inside a container that matches the Lambda runtime, which is required for native dependencies.
  • sam local invoke, sam local start-api and sam local start-lambda run functions and APIs locally in Docker containers that emulate Lambda, using event files generated by sam local generate-event.
  • sam sync deploys changes to a development stack quickly; with --watch it watches files and updates function code directly through service APIs rather than a full CloudFormation deployment. It is intended for development accounts only, because it bypasses the normal change process.
  • sam deploy packages artifacts to S3 or ECR and deploys the stack through a change set; --guided saves settings to samconfig.toml for later runs.
  • sam logs and sam traces retrieve CloudWatch Logs and X-Ray traces for the application.
  • sam pipeline bootstrap creates the IAM roles and artifact buckets for each deployment stage, and sam pipeline init generates a pipeline definition for CodePipeline or other CI systems.
Match the pairs

SAM CLI commands

Exam skills 2.1.1 · 1.3.2

Match each SAM CLI command with its purpose.

Log in to try this activity Interactive activities are free with an account.

Gradual Deployments with SAM

As described in the AWS CodeDeploy module, AutoPublishAlias and DeploymentPreference on a function make SAM create a CodeDeploy application and deployment group and shift traffic gradually between versions with alarm-based rollback and pre- and post-traffic hooks. API stages defined with AWS::Serverless::Api can also use CanarySetting for REST API canary releases. These features let a SAM template express the deployment strategy alongside the resources.

Worked example

From Laptop to Pipeline

A team develops an order API with SAM. Developers want fast feedback, and production deployments must use canary traffic shifting with automatic rollback.

  1. Develop

    Developers run sam local start-api for local tests and sam sync --watch against personal development stacks.

  2. Bootstrap

    sam pipeline bootstrap creates deployment roles and artifact buckets in the test and production accounts.

  3. Pipeline

    sam pipeline init generates a CodePipeline definition whose build stage runs sam build and sam package and whose deploy stages deploy the packaged template with CloudFormation.

  4. Safe releases

    Functions use AutoPublishAlias: live and DeploymentPreference with Canary10Percent5Minutes and error alarms.

Check yourself

Why should sam sync not be used to deploy to production?

Show answer

sam sync can update function code directly through service APIs and skip CloudFormation change sets, so production would drift from the template and bypass the reviewed pipeline. It is designed for development environments.

Exam Tips

Remember for the exam

  • SAM templates use Transform: AWS::Serverless-2016-10-31 and expand into CloudFormation; deploy with CAPABILITY_AUTO_EXPAND.
  • Use policy templates or connectors for least-privilege permissions; Globals share function settings.
  • sam build --use-container builds native dependencies for Lambda; sam local runs functions locally; sam sync is for development only.
  • sam pipeline bootstrap and sam pipeline init create stage resources and pipeline definitions.
  • AutoPublishAlias with DeploymentPreference gives canary or linear Lambda deployments through CodeDeploy.