This chapter covers the AWS Serverless Application Model (SAM), a framework for defining and deploying serverless applications on AWS. For the DVA-C02 exam, SAM is a critical topic under Domain 3: Deployment, Objective 3.2 (Deploy serverless applications). Approximately 10-15% of exam questions touch on SAM, often focusing on template syntax, the SAM CLI, and integration with other services like Lambda, API Gateway, and DynamoDB. You will be expected to understand how SAM simplifies serverless development, its key components, and how to use it for local testing and deployment.
Jump to a section
Imagine you want to build a house. You could individually order lumber, windows, doors, and plumbing fixtures, then hire separate contractors for framing, electrical, and roofing. That's like using raw AWS CloudFormation to define every IAM role, Lambda function, API Gateway resource, and DynamoDB table separately. Now imagine instead you use a prefab house blueprint from a catalog. The blueprint says '3-bedroom ranch with attached garage' and includes standard specifications for wall thickness, window sizes, and wiring. You give this blueprint to a general contractor who reads it and automatically orders all the correct materials and coordinates subcontractors. AWS SAM is that blueprint. It provides shorthand syntax (like AWS::Serverless::Function) that expands into multiple underlying CloudFormation resources. The SAM CLI 'translates' your template into raw CloudFormation, then deploys it. Just as the prefab blueprint ensures all parts fit together (e.g., windows match rough openings), SAM ensures your Lambda functions have the right IAM roles, API Gateway endpoints, and event source mappings. You don't worry about the individual nails and studs—you focus on the house design. But if you need custom features (like a non-standard window), you can add raw CloudFormation resources alongside SAM resources. The SAM CLI also provides a local testing environment (like a virtual walkthrough of the house) before you commit to construction.
What is AWS SAM?
AWS Serverless Application Model (SAM) is an open-source framework for building serverless applications. It extends AWS CloudFormation with simplified syntax specifically for serverless resources. SAM allows you to define serverless components—such as Lambda functions, API Gateway APIs, and DynamoDB tables—using a compact, high-level syntax. Under the hood, SAM transforms your template into a standard CloudFormation template that creates all the necessary resources.
Why SAM Exists
Before SAM, deploying a serverless application required writing verbose CloudFormation templates with many lines of boilerplate code. For example, a simple Lambda function behind API Gateway needed explicit definitions for:
The Lambda function itself
An IAM role with execution permissions
An API Gateway REST API
A resource and method for the API
Integration between API Gateway and Lambda
Appropriate permissions for API Gateway to invoke Lambda
SAM reduces this to a few lines. It also provides a CLI (sam) for local testing, packaging, and deployment, which CloudFormation alone lacks.
How SAM Works Internally
SAM operates in two phases: transformation and deployment.
Phase 1: Transformation
When you run sam deploy or aws cloudformation deploy with a SAM template, CloudFormation invokes a macro called AWS::Serverless-2016-10-31. This macro processes your template and expands each SAM resource into the underlying CloudFormation resources. For example, AWS::Serverless::Function expands to:
- AWS::Lambda::Function
- AWS::IAM::Role
- AWS::Lambda::Permission (if event sources are defined)
- Potentially other resources depending on the event source (e.g., AWS::ApiGateway::RestApi for HttpApi events)
The transformation happens server-side in CloudFormation. The resulting template is then used to create or update the stack.
Phase 2: Deployment
The transformed CloudFormation template is deployed as a standard CloudFormation stack. All SAM resources become actual AWS resources. The SAM CLI (sam deploy) automates this process, including packaging artifacts (zipping Lambda code, uploading to S3) and handling IAM capabilities.
Key SAM Resource Types
SAM defines several resource types that start with AWS::Serverless:::
- AWS::Serverless::Function: Defines a Lambda function. Key properties:
- CodeUri: Path to the function code (local or S3).
- Handler: Function handler (e.g., index.handler).
- Runtime: e.g., python3.9, nodejs18.x.
- Events: Event sources that trigger the function (e.g., API Gateway, S3, SNS, DynamoDB Streams).
- Policies: IAM policies attached to the function's role. Can be managed policy ARNs or inline policies.
- Environment: Environment variables.
- AutoPublishAlias: Enables traffic shifting for canary deployments.
- DeploymentPreference: Controls canary deployment behavior (e.g., Linear10PercentEvery1Minute).
- AWS::Serverless::Api: Defines an API Gateway REST API. Key properties:
- StageName: e.g., Prod.
- DefinitionBody or DefinitionUri: OpenAPI specification.
- Cors: CORS configuration.
- Auth: Authorization settings (e.g., Cognito, IAM, Lambda authorizer).
- EndpointConfiguration: e.g., REGIONAL, EDGE, PRIVATE.
AWS::Serverless::HttpApi: Defines an API Gateway HTTP API (faster, cheaper than REST API). Key properties similar to Api but simpler.
AWS::Serverless::SimpleTable: Defines a DynamoDB table with only a primary key. For advanced features, use AWS::DynamoDB::Table directly.
AWS::Serverless::LayerVersion: Defines a Lambda layer.
AWS::Serverless::Application: Nests another SAM/CloudFormation application.
AWS::Serverless::StateMachine: Defines a Step Functions state machine.
SAM Template Structure
A SAM template is a CloudFormation template with a Transform declaration:
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: My SAM application
Globals:
Function:
Timeout: 10
MemorySize: 128
Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: src/
Handler: index.handler
Runtime: nodejs18.x
Events:
HelloWorld:
Type: Api
Properties:
Path: /hello
Method: getThe Globals section allows setting shared properties for all functions, APIs, etc. in the template. This reduces duplication.
SAM CLI Commands
The SAM CLI (sam) provides several commands crucial for the exam:
- `sam init`: Initializes a new SAM project from a template (e.g., sam init --runtime python3.9).
- `sam build`: Builds your application by installing dependencies and packaging code. It looks for a requirements.txt (Python) or package.json (Node.js) and runs the appropriate build commands. It also copies source files to a .aws-sam build directory.
- `sam package`: Packages your application by uploading artifacts to S3 and producing a packaged template. Equivalent to aws cloudformation package.
- `sam deploy`: Deploys the application. Common options:
- --guided: Interactive mode that prompts for parameters.
- --stack-name: CloudFormation stack name.
- --s3-bucket: S3 bucket for artifacts.
- --capabilities CAPABILITY_IAM: Required because SAM creates IAM roles.
- --no-fail-on-empty-changeset: Prevents failure when no changes are made.
- `sam local invoke`: Invokes a Lambda function locally using a Docker container that mimics the Lambda runtime.
- `sam local start-api`: Starts a local HTTP server that emulates API Gateway and invokes Lambda functions.
- `sam logs`: Fetches logs from CloudWatch Logs for a function.
- `sam sync`: (Newer) Syncs local changes to the cloud for rapid development.
- `sam validate`: Validates your SAM template against the SAM specification.
- `sam delete`: Deletes the stack and associated artifacts.
Defaults and Timers
SAM sets sensible defaults for many properties:
Lambda function timeout: Default 3 seconds (can be set globally).
Lambda memory: Default 128 MB.
API Gateway stage name: Prod (for AWS::Serverless::Api).
API Gateway endpoint type: REGIONAL.
IAM role: SAM creates a basic execution role with AWSLambdaBasicExecutionRole managed policy.
Integration with Other Services
SAM integrates with:
- CloudFormation: As the underlying deployment engine.
- Lambda: For serverless compute.
- API Gateway: For REST and HTTP APIs.
- DynamoDB: Via SimpleTable or raw DynamoDB resources.
- S3: For event sources and artifact storage.
- SNS, SQS: As event sources for Lambda.
- Step Functions: Via AWS::Serverless::StateMachine.
- Cognito: For API authorization.
- CodeDeploy: For safe Lambda deployments with traffic shifting.
- CloudWatch: For logging and monitoring.
SAM Policy Templates
SAM provides predefined policy templates that attach common permissions to Lambda functions. Examples:
- S3CrudPolicy: Read/write access to a specific S3 bucket.
- DynamoDBCrudPolicy: Read/write access to a DynamoDB table.
- SQSPollerPolicy: Allows polling an SQS queue.
- CloudWatchPutMetricPolicy: Allows putting custom metrics.
You can reference these in the Policies property:
Policies:
- S3CrudPolicy:
BucketName: my-bucketSAM and CodeDeploy for Safe Deployments
SAM supports canary and linear deployments for Lambda functions using DeploymentPreference and AutoPublishAlias. This creates a CodeDeploy application that shifts traffic gradually. For example:
AutoPublishAlias: live
DeploymentPreference:
Type: Canary10Percent5MinutesThis publishes a new version, creates an alias live, and shifts 10% of traffic to the new version for 5 minutes before moving to 100%.
SAM vs Terraform
While Terraform is also used for infrastructure as code, SAM is AWS-native and deeply integrated with Lambda, API Gateway, and other serverless services. SAM templates are simpler for serverless workloads, but Terraform supports multi-cloud. For the DVA-C02, SAM is the expected tool for serverless deployment.
Common Pitfalls
Forgetting to specify CAPABILITY_IAM or CAPABILITY_NAMED_IAM during deployment.
Not running sam build before sam deploy when code changes.
Using sam local invoke without Docker installed.
Hardcoding environment-specific values instead of using parameters.
Overlooking the Globals section to reduce duplication.
Initialize SAM Project
Run `sam init` to create a new SAM project. You choose a runtime (e.g., Python 3.9), a template (e.g., Hello World), and a project name. SAM generates a folder structure with a `template.yaml` file (the SAM template), a `src/` directory for your code, and optionally a `events/` directory for test events. This step sets up the basic skeleton. The `template.yaml` includes a single `AWS::Serverless::Function` resource with an API Gateway event source. The generated code is a simple handler that returns a response. You can then modify the code and template to suit your application.
Build the Application
Run `sam build` in the project root. This command processes your source code: it installs dependencies (e.g., runs `pip install -r requirements.txt` for Python, `npm install` for Node.js), compiles any build-time artifacts, and copies everything to a `.aws-sam/build` directory. It also copies your SAM template and any nested stacks. The build step is required before local testing or deployment because it prepares the artifacts in the format Lambda expects. If you skip `sam build`, `sam deploy` will fail because the `CodeUri` path may not contain the built artifacts.
Local Testing with sam local invoke
Run `sam local invoke FunctionName` to test a Lambda function locally. This command uses a Docker container that mimics the Lambda runtime environment. It reads the function code from the `.aws-sam/build` directory, passes the event payload (you can provide one via `-e` or use a file), and returns the response. This allows you to debug without deploying. The Docker image is pulled from the public AWS Lambda runtime images. Ensure Docker is running. You can also use `sam local start-api` to start a local HTTP server that emulates API Gateway and invokes functions for HTTP requests.
Package the Application
Run `sam package --s3-bucket your-bucket` to upload your built artifacts to an S3 bucket and produce a packaged template. This command replaces local `CodeUri` paths with the S3 URI of the uploaded zip file. The packaged template is output as a JSON or YAML file (default `packaged.yaml`). This step is necessary before deployment because CloudFormation needs the artifacts to be in S3. The `sam deploy` command can automatically run `sam package` if you use the `--s3-bucket` flag.
Deploy the Application
Run `sam deploy --guided` for an interactive deployment. You specify the stack name, AWS region, capabilities (e.g., `CAPABILITY_IAM`), and whether to rollback on failure. SAM creates a CloudFormation stack with the transformed template. It creates all resources: Lambda functions, API Gateway, IAM roles, etc. After deployment, it outputs the API endpoint URL. You can also use `sam deploy --stack-name mystack --s3-bucket mybucket --capabilities CAPABILITY_IAM` for non-interactive deployment. SAM uses CloudFormation change sets to apply updates incrementally.
Scenario 1: Microservices API Backend
A company builds a REST API for a mobile app using multiple Lambda functions for different endpoints (users, orders, payments). They use SAM to define each function with its own API Gateway resource. The SAM template includes an AWS::Serverless::Api for the REST API with a custom domain and Cognito authorizer. Each function is defined with Events of type Api pointing to specific paths and methods. The Globals section sets a common timeout and memory size. The team uses sam local start-api for local development, which speeds up iteration. In production, they deploy with sam deploy --guided and use DeploymentPreference for canary releases. One challenge is managing environment-specific configuration (e.g., database table names). They use CloudFormation parameters and the Parameters section in the template. A misconfiguration—like forgetting to add CAPABILITY_IAM—causes deployment failures. Also, if the CodeUri points to a local path that doesn't exist after build, the packaged template references a missing zip file, causing a stack update failure. They learned to always run sam build before sam package or sam deploy.
Scenario 2: Event-Driven Data Processing Pipeline
A financial services company processes real-time transaction data. They use SAM to define Lambda functions triggered by S3 events (new files), SNS topics, and DynamoDB Streams. The SAM template includes an AWS::Serverless::Function for each processor, with Events of type S3, SNS, and DynamoDB. They use AWS::Serverless::SimpleTable for a DynamoDB table that stores processing status. The SAM Policies property attaches S3ReadPolicy and DynamoDBCrudPolicy to the functions. They use sam build with a custom build script to compile Java code. During deployment, they use --parameter-overrides to pass environment-specific values (e.g., S3 bucket names). A common issue is that the S3 event source requires the bucket to be in the same account and region. Also, if the function code has dependencies that are not included in the build, the function fails at runtime. They use sam local invoke with test events to validate. They also use sam logs to tail CloudWatch logs during testing.
Scenario 3: Serverless Web Application with Authentication
A startup builds a serverless web app with user authentication via Amazon Cognito. They use SAM to define an HTTP API (AWS::Serverless::HttpApi) with JWT authorizer. The SAM template includes a Lambda function for each API route. They use the Auth property on the API to specify the Cognito user pool. For the frontend, they host static files on S3 and CloudFront, but that part is outside SAM. During development, they use sam local start-api to test locally, but they need to mock Cognito tokens. In production, they deploy with sam deploy and use AWS::Serverless::LayerVersion for common dependencies (e.g., AWS SDK). They also use sam sync for rapid updates. A misconfiguration: if the Auth property is not set correctly, API Gateway returns 401 errors. They learned to test with actual Cognito tokens using sam local invoke with a token in the event.
DVA-C02 Exam Focus on SAM
The DVA-C02 exam tests SAM under Objective 3.2: Deploy serverless applications. You will encounter questions that require you to interpret SAM templates, identify correct CLI commands, and understand the transformation process. Key areas:
SAM Template Syntax: You must know the structure, including Transform: AWS::Serverless-2016-10-31, Globals, and resource types. Questions may ask which resource type to use for a given scenario (e.g., AWS::Serverless::Function for Lambda, AWS::Serverless::Api for REST API).
SAM CLI Commands: You need to know the purpose of sam init, sam build, sam package, sam deploy, sam local invoke, sam local start-api, sam logs, and sam validate. Common wrong answer: confusing sam build with sam package. Remember: sam build prepares artifacts locally; sam package uploads to S3.
Deployment Options: Understand --guided vs. non-interactive, --capabilities, --s3-bucket, and --no-fail-on-empty-changeset. The exam may ask what happens if you omit CAPABILITY_IAM—the deployment fails.
Local Testing: Know that sam local invoke and sam local start-api require Docker. They simulate the Lambda runtime environment. A common question: "How can you test a Lambda function locally without deploying?" Answer: Use sam local invoke.
Policy Templates: Be familiar with S3CrudPolicy, DynamoDBCrudPolicy, etc. The exam may ask which policy template grants read/write access to a DynamoDB table.
Safe Deployments: Understand AutoPublishAlias and DeploymentPreference. Know the difference between Canary10Percent5Minutes and Linear10PercentEvery1Minute.
Transformation: Remember that SAM transforms into CloudFormation. A question might ask: "What happens when you deploy a SAM template?" The answer: CloudFormation uses the SAM transform macro to expand resources.
Common Wrong Answers
Choosing `sam package` instead of `sam build` when the question asks about preparing dependencies locally. Candidates often confuse the two. sam build installs dependencies and copies code; sam package uploads to S3.
Thinking SAM is a separate service from CloudFormation. SAM is an extension of CloudFormation, not a standalone service.
Forgetting that `sam deploy` requires `--capabilities CAPABILITY_IAM`. Many questions include this as a distractor.
Believing that `sam local invoke` can test API Gateway features. It only tests the Lambda function; for API Gateway emulation, use sam local start-api.
Assuming SAM supports all CloudFormation resources. SAM is for serverless resources; for non-serverless resources, you use raw CloudFormation.
Edge Cases
Nested Applications: AWS::Serverless::Application allows nesting. The exam may ask how to include a pre-built serverless app from the AWS SAR.
Custom Runtimes: SAM supports custom runtimes via Runtime: provided.al2.
IAM Role Customization: If you need a custom IAM role, you can define it separately and reference it via the Role property.
Multiple Environments: Use parameters and sam deploy --parameter-overrides to deploy to dev, staging, prod.
How to Eliminate Wrong Answers
If a question mentions "local testing without Docker," eliminate sam local invoke because it requires Docker.
If the question asks about "uploading artifacts to S3," the answer is sam package or sam deploy with --s3-bucket.
If the question involves "creating a new project," look for sam init.
For "deploying a serverless application with minimal code," SAM is the correct tool, not raw CloudFormation.
For "traffic shifting," look for DeploymentPreference.
SAM is an extension of CloudFormation, not a separate service; it uses the transform macro AWS::Serverless-2016-10-31.
The SAM CLI command sam build prepares local artifacts; sam package uploads them to S3.
Deploying a SAM stack requires CAPABILITY_IAM because SAM creates IAM roles.
Local testing with sam local invoke or sam local start-api requires Docker.
SAM policy templates (e.g., S3CrudPolicy) simplify attaching common permissions to Lambda functions.
AutoPublishAlias and DeploymentPreference enable canary/linear deployments for Lambda.
The Globals section sets default properties for all resources of a type, reducing duplication.
SAM supports event sources: Api, HttpApi, S3, SNS, SQS, DynamoDB, Kinesis, CloudWatch Events, etc.
These come up on the exam all the time. Here's how to tell them apart.
AWS SAM
Simplified syntax for serverless resources (e.g., AWS::Serverless::Function).
Includes a CLI (sam) for local testing, packaging, and deployment.
Built-in policy templates for common permissions (e.g., S3CrudPolicy).
Supports canary and linear deployments via DeploymentPreference.
Best for serverless-first applications; reduces boilerplate.
Raw AWS CloudFormation
Verbose syntax; requires explicit definition of all resources (IAM roles, permissions, etc.).
No built-in local testing; relies on third-party tools or manual invocation.
No predefined policy templates; you must write full IAM policies.
No native support for traffic shifting; requires additional CodeDeploy configuration.
Best for infrastructure that includes both serverless and non-serverless resources.
sam local invoke
Invokes a single Lambda function with a provided event.
Does not start an HTTP server.
Used for unit testing a function in isolation.
Requires Docker and a Lambda runtime image.
Example: sam local invoke MyFunction -e event.json
sam local start-api
Starts a local HTTP server that emulates API Gateway.
Automatically routes HTTP requests to the correct Lambda function based on the template.
Used for integration testing of API endpoints.
Requires Docker and starts multiple containers for each function.
Example: sam local start-api --port 3000
Mistake
SAM is a separate service from CloudFormation.
Correct
SAM is an extension of CloudFormation. It uses a transform macro to convert SAM syntax into standard CloudFormation resources. The deployment still uses CloudFormation stacks.
Mistake
sam build uploads code to S3.
Correct
sam build only prepares artifacts locally in the .aws-sam/build directory. It does not upload anything to S3. The sam package or sam deploy command with --s3-bucket handles the upload.
Mistake
You can use sam local invoke to test API Gateway integrations.
Correct
sam local invoke tests only the Lambda function. To test API Gateway locally, you must use sam local start-api, which starts a local HTTP server that emulates API Gateway.
Mistake
SAM templates cannot include non-serverless resources.
Correct
SAM templates can include any CloudFormation resource. You can mix AWS::Serverless::* with AWS::* resources in the same template.
Mistake
SAM automatically handles all IAM roles without any input.
Correct
SAM creates a basic execution role, but for custom permissions you must specify policies. If you omit CAPABILITY_IAM during deployment, the deployment fails.
Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.
sam build prepares your application for deployment by installing dependencies, compiling code, and copying artifacts to the .aws-sam/build directory. It does not upload anything to AWS. sam package uploads the built artifacts to an S3 bucket and creates a packaged template that references the S3 locations. In short, sam build is a local preparation step, while sam package is the upload step. Both are often combined via sam deploy --s3-bucket which runs build and package internally.
Use sam local invoke FunctionName -e event.json. This requires Docker to be running. It spins up a Docker container that mimics the Lambda runtime, passes the event payload, and returns the response. For testing API Gateway endpoints, use sam local start-api which starts a local HTTP server. Ensure you have run sam build first so the code is in the .aws-sam/build directory.
This declaration tells CloudFormation to process the template with the SAM transform macro. The macro expands each AWS::Serverless::* resource into the underlying CloudFormation resources (e.g., AWS::Lambda::Function, AWS::IAM::Role, AWS::Lambda::Permission). This transformation happens server-side during stack creation or update. Without this transform, CloudFormation would not recognize SAM resource types.
Yes, you can include any CloudFormation resource in a SAM template. SAM resources are just a subset. You can mix AWS::Serverless::Function with AWS::EC2::Instance in the same template. However, SAM's benefits (simplified syntax, local testing) apply only to serverless resources. For non-serverless resources, you write standard CloudFormation syntax.
SAM policy templates are predefined IAM policy documents that grant common permissions. For example, S3CrudPolicy grants s3:GetObject, s3:PutObject, s3:DeleteObject on a specific bucket. You use them in the Policies property of a function: Policies: - S3CrudPolicy: { BucketName: my-bucket }. This attaches the corresponding IAM policies to the function's execution role. Other templates include DynamoDBCrudPolicy, SQSPollerPolicy, etc.
Set AutoPublishAlias to a name (e.g., live) and add DeploymentPreference to your function. For example: AutoPublishAlias: live, DeploymentPreference: { Type: Canary10Percent5Minutes }. This creates a CodeDeploy application that shifts 10% of traffic to the new version for 5 minutes, then moves to 100%. Other types include Linear10PercentEvery1Minute and AllAtOnce.
The Globals section allows you to set default properties for all resources of a given type. For example, you can set a default Timeout and MemorySize for all functions, or a default StageName for all APIs. This reduces duplication. Properties set at the resource level override the global defaults. The Globals section is optional but recommended for consistency.
You've just covered AWS Serverless Application Model (SAM) — now see how well it sticks with free DVA-C02 practice questions. Full explanations included, no account needed.
Done with this chapter?