Lesson 2 of 4 AWS SAM and CloudFormation

Building Serverless Applications with AWS SAM Templates and the SAM CLI

This lesson explains how the AWS Serverless Application Model (AWS SAM) extends CloudFormation with shorthand resources for serverless applications, and adds a CLI for building, testing and deploying them.

Learning outcomes

After completing this lesson, you will be able to:

  • Explain how the SAM transform expands SAM resources into CloudFormation resources.
  • Describe the SAM CLI commands used at each stage of development, from sam init to sam deploy.

SAM templates

The AWS Serverless Application Model (SAM) is an extension of CloudFormation for serverless applications. The line Transform: AWS::Serverless-2016-10-31 identifies a SAM template and tells CloudFormation to expand each SAM resource into the full set of CloudFormation resources it represents before deploying. Because the result is ordinary CloudFormation, a SAM template can also contain any CloudFormation resource.

The most important resource is AWS::Serverless::Function. A few lines declare the code, handler and runtime, and SAM creates the Lambda function, an execution role with the listed policies, and the event sources named under Events, such as an API route, an S3 notification or an SQS event source mapping. With AutoPublishAlias, it also publishes a version and points an alias at it on every deployment. AWS::Serverless::Api and AWS::Serverless::HttpApi create API Gateway REST and HTTP APIs, AWS::Serverless::SimpleTable creates a DynamoDB table with a single key, and AWS::Serverless::LayerVersion creates a layer. The following table summarises these resource types.

SAM resourceCreates
AWS::Serverless::FunctionA Lambda function with its role, event sources and optional alias
AWS::Serverless::Api / HttpApiAn API Gateway REST or HTTP API
AWS::Serverless::SimpleTableA DynamoDB table with a single key
AWS::Serverless::LayerVersionA Lambda layer

The following list describes further sections and properties of SAM templates.

  • Globals sets properties shared by every function, such as runtime, timeout and tracing.
  • Policy templates such as DynamoDBCrudPolicy generate least-privilege IAM permissions in one line.
  • DeploymentPreference uses CodeDeploy to shift traffic gradually, with alarms and pre- and post-traffic hooks that trigger automatic rollback.

Example. SAM expands this into a function, role, REST API, table, version and alias, and a canary deployment that shifts 10% of traffic for five minutes.

Transform: AWS::Serverless-2016-10-31
Globals:
  Function:
    Runtime: python3.13
    Timeout: 10
    Tracing: Active
Resources:
  OrdersFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/
      Handler: app.handler
      AutoPublishAlias: live
      DeploymentPreference:
        Type: Canary10Percent5Minutes
      Environment:
        Variables:
          TABLE_NAME: !Ref OrdersTable
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref OrdersTable
      Events:
        CreateOrder:
          Type: Api
          Properties: {Path: /orders, Method: post}
  OrdersTable:
    Type: AWS::Serverless::SimpleTable

The SAM CLI

The SAM CLI supports each stage of developing a serverless application. sam init creates a project from a template. sam build prepares the code for deployment: it installs each function's dependencies, such as the packages in requirements.txt, and writes the result to .aws-sam/build; with --use-container it builds inside a Lambda-like container, which matters for dependencies with native code. sam local commands run functions and APIs on the developer's machine.

sam deploy uploads the built code to S3, or container images to ECR, and deploys the template through a CloudFormation change set; --guided asks for the stack name, Region and other settings once and saves them in samconfig.toml. During development, sam sync updates code changes directly through service APIs, which takes seconds rather than minutes, but it bypasses CloudFormation for those changes and is not intended for production. sam pipeline init generates a CI/CD pipeline configuration for the project. The following table summarises the commands.

CommandWhat it does
sam initScaffolds a project
sam buildResolves dependencies and packages the code
sam local invoke, sam local start-apiRuns functions and APIs locally in containers
sam deploy --guidedUploads artifacts to S3 (or ECR) and deploys through a change set; saves answers to samconfig.toml
sam syncPushes changes quickly during development
sam pipeline initGenerates CI/CD pipelines
sam build && sam deploy --guided     # first deployment; answers are saved to samconfig.toml
Worked example

What SAM generates for you

A 20-line SAM template defines a function with an API event, a table and a canary deployment. After deployment, the stack's processed template in the CloudFormation console shows what SAM expanded:

SAM resource or propertyCloudFormation resources created
AWS::Serverless::FunctionLambda function and its IAM execution role
Events: ApiAPI Gateway REST API, stage, deployment and Lambda permission
Policies: DynamoDBCrudPolicyAn inline policy scoped to the table
AutoPublishAlias: liveA Lambda version and the live alias
DeploymentPreferenceA CodeDeploy application, deployment group and role
AWS::Serverless::SimpleTableA DynamoDB table

Roughly a dozen resources come from a template a fraction of the size, which is why SAM is the default answer for packaging and deploying serverless applications.

Check yourself

What does the line Transform: AWS::Serverless-2016-10-31 do in a template?

Show answer

It tells CloudFormation to expand SAM resources, such as AWS::Serverless::Function, into the full CloudFormation resources, including roles, permissions and event sources, during deployment.

Exam Tips

Remember for the exam

  • To test Lambda functions locally, use sam local invoke or sam local start-api.
  • The Transform line identifies a SAM template.
  • To share a timeout and runtime across all functions, use the SAM Globals section.
  • To store deployment settings for each environment, use samconfig.toml.