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 type | Creates | Notes |
|---|---|---|
| AWS::Serverless::Function | A Lambda function, its role and event source integrations | Events, policies, AutoPublishAlias and DeploymentPreference |
| AWS::Serverless::Api | An API Gateway REST API | Stages, authorisers, OpenAPI definitions, canary settings |
| AWS::Serverless::HttpApi | An API Gateway HTTP API | Lower cost and latency, JWT authorisers |
| AWS::Serverless::SimpleTable | A DynamoDB table with a single-attribute primary key | For simple tables; use AWS::DynamoDB::Table otherwise |
| AWS::Serverless::LayerVersion | A Lambda layer version | Shared libraries |
| AWS::Serverless::StateMachine | A Step Functions state machine | Definition substitutions and policy templates |
| AWS::Serverless::Application | A nested application | From the AWS Serverless Application Repository or a local template |
| AWS::Serverless::Connector | IAM permissions between two resources | Generates 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 initcreates a project from a template.sam buildresolves dependencies and builds each function into.aws-sam/build;--use-containerbuilds inside a container that matches the Lambda runtime, which is required for native dependencies.sam local invoke,sam local start-apiandsam local start-lambdarun functions and APIs locally in Docker containers that emulate Lambda, using event files generated bysam local generate-event.sam syncdeploys changes to a development stack quickly; with--watchit 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 deploypackages artifacts to S3 or ECR and deploys the stack through a change set;--guidedsaves settings tosamconfig.tomlfor later runs.sam logsandsam tracesretrieve CloudWatch Logs and X-Ray traces for the application.sam pipeline bootstrapcreates the IAM roles and artifact buckets for each deployment stage, andsam pipeline initgenerates a pipeline definition for CodePipeline or other CI systems.
SAM CLI commands
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.
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.
-
Develop
Developers run sam local start-api for local tests and sam sync --watch against personal development stacks.
-
Bootstrap
sam pipeline bootstrap creates deployment roles and artifact buckets in the test and production accounts.
-
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.
-
Safe releases
Functions use AutoPublishAlias: live and DeploymentPreference with Canary10Percent5Minutes and error alarms.
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.