Sub topic 12
Deploying repeatably with AWS SAM
This chapter assumes you can write a Lambda handler, know what memory, timeout and an execution role do, and have the AWS CLI configured with credentials. It also assumes you have installed the SAM CLI and Docker. Docker is only needed for local invocation and container builds.
Why click-built functions don't scale
You can create a function in the console by uploading a zip file and attaching a role. That works once. It fails when you need a second environment, a teammate's review, or a rollback. Nobody can tell which settings differ between staging and production, and nobody can rebuild the setup after someone deletes it.
Infrastructure as code (IaC) fixes this by describing resources in a file you keep in version control. The AWS Serverless Application Model (SAM) is an IaC tool for serverless applications. It has two parts:
- A template syntax, which is an extension of AWS CloudFormation.
- A command line tool (
sam) that builds, tests and deploys the template.
SAM is not a separate deployment engine. A SAM template is a CloudFormation template with a Transform: AWS::Serverless-2016-10-31 line. When you deploy, CloudFormation expands each short AWS::Serverless::* resource into the longer standard resources, such as a function, an IAM role, an event source mapping and a permission. You get a stack, change sets, drift detection and rollback from CloudFormation.
Anatomy of a SAM template
The template below defines the order-creation function from the handler chapter. It includes its table and an HTTP endpoint.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
OrdersFunction:
Type: AWS::Serverless::Function
Properties:
Handler: app.handler
Runtime: python3.12
CodeUri: src/
MemorySize: 256
Timeout: 10
Environment:
Variables:
TABLE_NAME: !Ref OrdersTable
Policies:
- DynamoDBCrudPolicy:
TableName: !Ref OrdersTable
Events:
CreateOrder:
Type: HttpApi
Properties:
Path: /orders
Method: post
OrdersTable:
Type: AWS::Serverless::SimpleTableEach part maps to a concept from earlier chapters:
| Template element | What it controls |
|---|---|
| `Handler`, `Runtime`, `CodeUri` | Which file and function Lambda calls, the language version, and the folder to package. `app.handler` with `CodeUri: src/` means the function `handler` in `src/app.py`. |
| `MemorySize`, `Timeout` | Function configuration. Memory is in MB and timeout is in seconds. |
| `Environment` | Environment variables. `!Ref OrdersTable` resolves to the table name, so the code never hardcodes it. |
| `Policies` | The execution role. SAM creates the role for you and attaches the policy. |
| `Events` | Triggers. SAM creates the API and the permission that lets it invoke the function. |
Policy templates keep roles narrow
DynamoDBCrudPolicy is a SAM policy template. It expands to an IAM policy that allows read and write actions on one named table. It does not grant access to every table. Other templates include SQSPollerPolicy, S3ReadPolicy and SNSPublishMessagePolicy. If no template fits, write an inline policy statement under Policies. Avoid AWSLambdaFullAccess-style managed policies, which grant far more than a function needs.
Globals avoid repetition
When several functions share settings, move them to a Globals section at the top level:
Globals:
Function:
Runtime: python3.12
Timeout: 10
MemorySize: 256
Tracing: Active
Environment:
Variables:
LOG_LEVEL: INFOProperties set on an individual function are merged with the globals. Scalar values on the function override the global value. Lists, such as layers, are appended.
Know what SimpleTable leaves out
AWS::Serverless::SimpleTable is a shortcut for a table with one string key named id. It cannot define sort keys, secondary indexes or a custom billing mode. For anything beyond a demo, use AWS::DynamoDB::Table directly. SAM templates can mix SAM and plain CloudFormation resources freely.
Adding more triggers
The same Events block can connect other sources. This example adds an SQS queue that feeds a worker function and turns on partial batch responses, so the handler's batchItemFailures return value takes effect.
OrdersQueue:
Type: AWS::SQS::Queue
Properties:
VisibilityTimeout: 60
WorkerFunction:
Type: AWS::Serverless::Function
Properties:
Handler: worker.handler
Runtime: python3.12
CodeUri: src/
Timeout: 10
Events:
FromQueue:
Type: SQS
Properties:
Queue: !GetAtt OrdersQueue.Arn
BatchSize: 10
FunctionResponseTypes:
- ReportBatchItemFailuresSet the queue's visibility timeout to at least six times the function timeout, as AWS recommends for SQS sources. Here the timeout is 10 seconds and the visibility timeout is 60. If the visibility timeout is shorter than the function can run, messages become visible again while still being processed and get handled twice.
The deploy workflow
The standard loop has four commands.
sam validate --lint
sam build
sam local invoke OrdersFunction --event events/create-order.json
sam deploy --guidedsam validate --lintchecks the template for syntax and common mistakes before anything is built.sam buildcopies your code into.aws-sam/build/, installs dependencies fromrequirements.txt(or the equivalent for your language), and writes a processed template there. Deploy from that output, not from your source folder.sam local invokeruns the function in a Docker container that imitates the Lambda runtime. The event file is a JSON document in the shape the real trigger sends. Local runs still call real AWS services if the code does, using your local credentials.sam deploy --guidedasks for a stack name, region and options, then saves your answers tosamconfig.toml.
After the first deploy, run sam deploy alone. It reads samconfig.toml, so the command is the same for every teammate and every CI run.
What deploy does
sam deploy zips each function's code and uploads it to an S3 bucket. By default SAM creates and manages a bucket for this. It then asks CloudFormation to build a change set, which is a preview of resources to add, modify or replace. Unless you pass --no-confirm-changeset, you review the change set before it runs. Because every deployment is a change set against the same stack, deploying twice with no changes does nothing.
Capabilities
When the template creates IAM roles, CloudFormation requires explicit acknowledgment. SAM's guided mode records CAPABILITY_IAM in samconfig.toml. If you name your roles yourself, you need CAPABILITY_NAMED_IAM. A deploy that fails with InsufficientCapabilitiesException means this acknowledgment is missing.
Outputs, parameters and environments
Expose values you need after deployment, such as the endpoint URL, in an Outputs section:
Outputs:
OrdersApiUrl:
Description: Invoke URL for POST /orders
Value: !Sub "https://${ServerlessHttpApi}.execute-api.${AWS::Region}.amazonaws.com/orders"ServerlessHttpApi is the logical ID SAM gives to the implicit HTTP API it creates when a function has an HttpApi event. To run several environments from one template, add a Parameters section such as Stage and deploy it once per environment with different stack names:
sam deploy --stack-name orders-staging --parameter-overrides Stage=staging
sam deploy --stack-name orders-prod --parameter-overrides Stage=prodSeparate stacks keep resources apart. Deleting staging cannot touch production.
Faster iteration with sam sync
A full deploy takes a minute or more. sam sync --stack-name orders-staging --watch watches your files. For code-only changes it updates the function directly through the Lambda API and skips CloudFormation. For template changes it falls back to a deploy. This makes it good for development stacks. It makes the live resources differ from what the last CloudFormation deploy recorded, so do not use it on production.
Common errors and fixes
- Function fails with
No module named 'app'orHandler not found.HandlerandCodeUrido not match the file layout. Check thatsrc/app.pydefineshandler. - The stack is in
ROLLBACK_COMPLETE. The first creation failed and CloudFormation cannot update a stack in this state. Delete the stack withsam delete, fix the cause and deploy again. AccessDeniedat runtime but the deploy succeeded. The code touches a resource the role does not cover. Add a narrow policy toPoliciesand redeploy. Do not widen it to*.- A change replaces a resource and loses data. Renaming a table's logical ID or changing an immutable property makes CloudFormation create a new table and delete the old one. Read the change set for
Replacement: True, and addDeletionPolicy: Retainto stateful resources. - Local invoke works but the deployed function fails. Local runs use your credentials and your machine's environment variables. The deployed function uses its execution role and the template's
Environmentblock.
Exercise
You change the Timeout of OrdersFunction from 10 to 30 in template.yaml, then run sam deploy without running sam build first. The deployed function still shows a 10-second timeout. What is the most likely cause, and what should you run instead?
Show answer
sam deploy uses the processed template in .aws-sam/build/ from the last sam build, so the old template was deployed again. Run sam build and then sam deploy. You can also use sam build && sam deploy to prevent skipping the build.
Exercise
Your SQS-triggered function returns batchItemFailures, but one bad message still causes the entire batch to be retried. Which line in the SAM template is probably missing, and where does it go?
Show answer
FunctionResponseTypes: [ReportBatchItemFailures] is missing under the Properties of the SQS event. Without it, Lambda ignores the returned list and treats any exception or failed batch as a failure of all messages.