☰ All modules Tier 2 · SAM (Serverless Application Model) GuideCheat sheet ‹ cloudformationcdk ›
Contents
  1. How SAM appears on DVA-C02
  2. 1. SAM templates and the Serverless transform
  3. 2. The Function resource and event sources
  4. 3. APIs tables layers and other serverless resources
  5. 4. The Globals section
  6. 5. Permissions with policy templates and connectors
  7. 6. Creating and building projects with sam init and sam build
  8. 7. Packaging and deploying with sam package and sam deploy
  9. 8. Configuration files and multiple environments
  10. 9. SAM Accelerate and testing in the cloud
  11. 10. Local testing with sam local and generated events
  12. 11. Automatic versions and aliases with AutoPublishAlias
  13. 12. Traffic shifting with DeploymentPreference hooks and alarms
  14. 13. Serverless Application Repository and nested applications
  15. Quick decision rules
  16. Changed vs older material

SAM (Serverless Application Model) — DVA-C02 Mastery Guide

  • Sources: course chapter 18 (AWS Serverless Application Model). The course serves as the syllabus only; all wording here is original.
  • Written 2026-10-12; values checked against AWS docs on 2026-10-12 (AWS SAM Developer Guide, CloudFormation, CodeDeploy, Serverless Application Repository and Lambda documentation). The marker ⚠️ Changed: <current>. Older material may say <old>. flags a value or behaviour that differs from the course or older practice tests: learn the current value. ⚠️ unverified marks something AWS documentation did not confirm: don't build an exam answer on it. Counts that keep growing (resource types, policy templates, CLI options) carry their date. Every change is listed in Changed vs older material.
  • Tier 2 (deployment and messaging), bank target 30 questions. Domain: Deployment (the only domain of this module).
  • How to use it: /explain <topic> teaches from these sections (concept → exam facts → developer angle → traps → 3 check questions); /quiz sam asks bank questions whose source_note links point at the ## N. headings below; /drill sam fires short recall prompts from notes/sam-cheat-sheet.md. Suggested loop: read a section and answer its practice questions before opening the answers → /explain what is still unclear → /quiz sam → /drill sam.
  • Owned by other modules (one-line pointers only here): Lambda versions, alias weights, concurrency, SnapStart and limits → notes/lambda-guide.md; API Gateway stages, authorizers, CORS and canary releases → notes/api-gateway-guide.md; template sections, intrinsic functions, change sets, rollback and nested stacks → notes/cloudformation-guide.md; CodeDeploy appspec, EC2/ECS deployments and CodePipeline → notes/cicd-guide.md; CDK and using the SAM CLI with CDK → notes/cdk-guide.md; Step Functions and AppSync → notes/other-services-guide.md; X-Ray and CloudWatch → notes/monitoring-guide.md; CLI profiles and credentials → notes/cli-sdk-policies-guide.md.

How SAM appears on DVA-C02

SAM is a Deployment-domain topic. Questions treat it as the shortest path from code to a working serverless stack and ask which SAM feature or command solves a delivery problem:

Typical question shapes: "Which line turns a CloudFormation template into a SAM template?"; "Which command gives the fastest feedback during development?"; "Release the new version to 10 % of traffic, then to everyone, with automatic rollback"; "Grant the function read access to one table with the least effort"; "Test the function locally with an S3 event"; "Deploy the same template to dev and prod with different parameters"; "Share the application with every account in the organization".

Deciding constraints: LEAST operational overhead (SAM shorthand, policy templates and the built-in CodeDeploy integration instead of scripts), fastest feedback (sam sync, local tests), safest release (canary or linear + alarms + hooks), least privilege (resource-scoped templates, connectors, OIDC for pipelines), fewest code changes (one template property instead of new tooling).

Out of scope: Docker or operating-system administration for the local tools, and network design for functions in a VPC (see notes/vpc-guide.md).

# Topic Why it is on the exam
1 SAM templates and the Serverless transform The Transform line, required sections, how the shorthand becomes CloudFormation
2 The Function resource and event sources What one AWS::Serverless::Function generates; events, roles, URLs, DLQs
3 APIs tables layers and other serverless resources REST vs HTTP vs WebSocket APIs, SimpleTable limits, layers, state machines
4 The Globals section Shared settings and the replace / merge / prepend override rules
5 Permissions with policy templates and connectors Least privilege in one line; the {} rule; connectors
6 Creating and building projects with sam init and sam build Scaffolding, dependency builds, build containers, esbuild, validation
7 Packaging and deploying with sam package and sam deploy Artifacts in S3/ECR, change sets, capabilities, CI flags, clean-up
8 Configuration files and multiple environments samconfig.toml environments, precedence, sam pipeline
9 SAM Accelerate and testing in the cloud sam sync modes and drift, sam remote invoke, logs and traces
10 Local testing with sam local and generated events invoke, generate-event, start-api, start-lambda, limits of local tests
11 Automatic versions and aliases with AutoPublishAlias When a new version is published and what points at the alias
12 Traffic shifting with DeploymentPreference hooks and alarms Canary, linear, all at once; hooks, alarms, rollback, generated CodeDeploy resources
13 Serverless Application Repository and nested applications Publish, share, capabilities, AWS::Serverless::Application

1. SAM templates and the Serverless transform

Concept

Exam facts

Developer angle

A complete minimal SAM template (HTTP API → function → table):

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Parameters:
  Stage:
    Type: String
    AllowedValues: [dev, prod]
    Default: dev
Resources:
  OrdersTable:
    Type: AWS::Serverless::SimpleTable
  CreateOrderFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/create_order/
      Handler: app.handler
      Runtime: python3.13
      Environment:
        Variables:
          TABLE_NAME: !Ref OrdersTable
          STAGE: !Ref Stage
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref OrdersTable
      Events:
        CreateOrder:
          Type: HttpApi
          Properties:
            Path: /orders
            Method: post
Outputs:
  ApiUrl:
    Value: !Sub 'https://${ServerlessHttpApi}.execute-api.${AWS::Region}.amazonaws.com/'

Check the template, then look at what the transform produced:

sam validate --lint                          # SAM validation plus cfn-lint rules
sam list resources --stack-name orders-dev   # logical IDs generated by the transform
aws cloudformation get-template --stack-name orders-dev \
  --template-stage Processed --query TemplateBody

Traps

Practice questions

  1. A developer copies a template from a colleague. It declares several AWS::Serverless::Function resources, but CloudFormation rejects it because it does not recognize those resource types. Which change makes the template deployable with the LEAST effort?

    • A. Add AWSTemplateFormatVersion: '2010-09-09' as the first line of the template file.
    • B. Add Transform: AWS::Serverless-2016-10-31 at the top level of the template.
    • C. Move the function definitions into a Globals section.
    • D. Deploy the template with the CAPABILITY_NAMED_IAM capability.
  2. A CI job creates a stack by calling aws cloudformation create-stack directly with a SAM template, without creating a change set first. The template's functions use execution roles that SAM generates without custom names. Which TWO changes to the call are required? (Select TWO.)

    • A. Pass --disable-rollback.
    • B. Add CAPABILITY_IAM to --capabilities.
    • C. Add CAPABILITY_RESOURCE_POLICY to --capabilities.
    • D. Add CAPABILITY_AUTO_EXPAND to --capabilities.
    • E. Pass a CloudFormation service role with --role-arn.
Answers
  1. B. Without the transform declaration CloudFormation treats AWS::Serverless::* as unknown types. A is optional and changes nothing; C is wrong because Globals holds shared properties, not resources; D concerns IAM acknowledgment, not resource types.
  2. B, D. Generated roles are IAM resources (CAPABILITY_IAM), and creating a stack directly from a template with a macro needs CAPABILITY_AUTO_EXPAND. C is an acknowledgment used by the Serverless Application Repository, not a value CreateStack accepts; A changes failure handling and E changes which role CloudFormation uses, and neither acknowledges anything.

2. The Function resource and event sources

Concept

Exam facts

Developer angle

Three functions, three trigger styles (push, poll, schedule):

Globals:
  Function:
    Runtime: python3.13
    Handler: app.handler
Resources:
  UploadsBucket:
    Type: AWS::S3::Bucket
  OrdersQueue:
    Type: AWS::SQS::Queue
  ReportFailures:
    Type: AWS::SQS::Queue
  ThumbnailFunction:                         # push: S3 notification + invoke permission
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/thumbnail/
      Events:
        NewUpload:
          Type: S3
          Properties:
            Bucket: !Ref UploadsBucket       # must be a bucket of this template
            Events: s3:ObjectCreated:*
  OrderWorkerFunction:                       # poll: event source mapping
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/worker/
      Events:
        FromQueue:
          Type: SQS
          Properties:
            Queue: !GetAtt OrdersQueue.Arn
            BatchSize: 10
            FunctionResponseTypes: [ReportBatchItemFailures]
  NightlyReportFunction:                     # schedule: EventBridge Scheduler
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/report/
      DeadLetterQueue:                       # failed asynchronous invocations
        Type: SQS
        TargetArn: !GetAtt ReportFailures.Arn
      Events:
        Nightly:
          Type: ScheduleV2
          Properties:
            ScheduleExpression: cron(0 2 * * ? *)

After deployment, sam list resources --stack-name media-dev shows the generated roles, the S3 invoke permission, the event source mapping and the EventBridge Scheduler schedule; sam list endpoints lists function URLs and API endpoints when a stack has them.

Traps

Practice questions

  1. A developer adds an S3 event to a function so that uploads trigger it. The bucket belongs to another team's stack, and the deployment fails. The teams agree that this application can create and own its own uploads bucket instead. What should the developer do?

    • A. Pass the other stack's exported bucket name to the event's Bucket property with Fn::ImportValue.
    • B. Add the S3ReadPolicy policy template for the existing bucket to the function.
    • C. Declare the bucket in this template and reference it with !Ref in the event's Bucket property.
    • D. Deploy the stack with the CAPABILITY_AUTO_EXPAND capability.
  2. A developer deploys a function that declares Role: arn:aws:iam::111122223333:role/orders-exec, a Policies entry with DynamoDBReadPolicy, and Tracing: Active. After deployment, reads fail with AccessDenied and no traces arrive in X-Ray. Which TWO statements explain the behaviour? (Select TWO.)

    • A. SAM ignores the Policies property when Role is specified.
    • B. SAM merges policy templates into the role passed in Role.
    • C. SAM adds AWSXrayWriteOnlyAccess only to execution roles that it generates.
    • D. SAM rejects Tracing: Active for functions that use an existing role.
    • E. Policy templates take effect only when they are declared under Globals.
Answers
  1. C. The S3 event only accepts a reference to a bucket defined in the same template. A fails because the property accepts only such a reference; B grants access but creates no trigger; D is unrelated to event wiring.
  2. A, C. A supplied role replaces the generated one, so neither Policies nor the automatic X-Ray policy is applied; add both permissions to orders-exec. B is the opposite of the documented behaviour; D is wrong because tracing is configured but lacks permissions; E is wrong because Policies can't be set in Globals at all.

3. APIs tables layers and other serverless resources

Concept

Beyond functions, SAM offers shorthand for the other serverless building blocks: three API Gateway API types, a single-key DynamoDB table, Lambda layers, Step Functions state machines, AppSync GraphQL APIs, nested applications (§13), connectors (§5) and, more recently, Lambda compute resources. Each expands into the matching CloudFormation resources; for anything the shorthand can't express, declare the full CloudFormation type in the same template.

Exam facts

SAM type Expands to Facts to know
Api AWS::ApiGateway::RestApi, Deployment, Stage REST API. StageName required (implicit API: Prod). Auth: Cognito user pool, Lambda TOKEN / REQUEST and AWS_IAM authorizers, ApiKeyRequired, UsagePlan (adds usage plan, key and API key resources), ResourcePolicy. Also Cors, CanarySetting, caching, EndpointConfiguration, OpenAPI through DefinitionBody or DefinitionUri
HttpApi AWS::ApiGatewayV2::Api, Stage HTTP API (lower cost and latency); default stage $default; Auth with JWT authorizers among others; CorsConfiguration needs DefinitionBody
WebSocketApi AWS::ApiGatewayV2::Api (WebSocket), Stage RouteSelectionExpression (for example $request.body.action) and Routes ($connect, $disconnect, $default, custom) are required; stage default unless StageName; Auth applies to $connect
SimpleTable AWS::DynamoDB::Table Single-attribute primary key only (default id, String); without ProvisionedThroughput the table is PAY_PER_REQUEST; PrimaryKey can't change after creation; sort keys, indexes, streams or TTL → AWS::DynamoDB::Table
LayerVersion AWS::Lambda::LayerVersion ContentUri, CompatibleRuntimes, CompatibleArchitectures, RetentionPolicy: Retain or Delete; SAM changes the logical ID on each update so old versions survive; since CloudFormation added UpdateReplacePolicy, AWS recommends plain AWS::Lambda::LayerVersion with UpdateReplacePolicy: Retain instead, which also keeps the old version when an update replaces it
StateMachine AWS::StepFunctions::StateMachine Definition or DefinitionUri; DefinitionSubstitutions; Policies accepts policy templates; Type STANDARD (default) or EXPRESS; Events; optional AutoPublishAlias + DeploymentPreference
GraphQLApi AppSync resources GraphQL API with resolvers (notes/other-services-guide.md)
Application AWS::CloudFormation::Stack Nested application from SAR or a template (§13)
Connector IAM managed policies or resource permissions (AWS::Lambda::Permission, queue or topic policies) Read and Write permissions between resources (§5)
CapacityProvider AWS::Lambda::CapacityProvider Lambda Managed Instances on EC2; VpcConfig required; functions attach through CapacityProviderConfig
MicrovmImage, NetworkConnector AWS::Lambda::MicrovmImage, AWS::Lambda::NetworkConnector Newer Lambda MicroVM images and VPC egress connectors; not DVA-C02 material

Developer angle

REST API with a Cognito authorizer and CORS, plus a layer that sam build builds:

Globals:
  Api:
    OpenApiVersion: '3.0.1'              # no extra "Stage" stage
Resources:
  ShopUserPool:
    Type: AWS::Cognito::UserPool
  OrdersApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: prod
      Cors: "'https://shop.example.com'"
      Auth:
        DefaultAuthorizer: ShopUsers
        Authorizers:
          ShopUsers:
            UserPoolArn: !GetAtt ShopUserPool.Arn
  SharedLibs:
    Type: AWS::Serverless::LayerVersion
    Properties:
      ContentUri: layers/shared/
      CompatibleRuntimes: [python3.12]
      RetentionPolicy: Retain
    Metadata:
      BuildMethod: python3.12            # sam build installs the layer's requirements
  ListOrdersFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/list_orders/
      Handler: app.handler
      Runtime: python3.12
      Layers: [!Ref SharedLibs]
      Events:
        List:
          Type: Api
          Properties:
            RestApiId: !Ref OrdersApi
            Path: /orders
            Method: get

Traps

Practice questions

  1. A team's REST API is built only from Api events on several functions, and after deployment it shows two stages, Prod and Stage. The team wants only Prod with the fewest template changes. What should the developer do?

    • A. Delete the Stage stage in the API Gateway console after each deployment.
    • B. Change every function's events from Api to HttpApi.
    • C. Declare an AWS::Serverless::Api with StageName: Prod and reference it with RestApiId from every event.
    • D. Set OpenApiVersion: '3.0.1' under Globals → Api.
  2. A developer is defining a DynamoDB table in a SAM template. Items need a partition key and a sort key, and one access pattern needs a global secondary index. Which TWO statements are correct? (Select TWO.)

    • A. Add the sort key as a second entry of the SimpleTable PrimaryKey property.
    • B. SAM templates can't contain AWS::DynamoDB::Table resources, so a separate stack is needed.
    • C. Declare the table as an AWS::DynamoDB::Table resource in the SAM template.
    • D. SimpleTable creates a provisioned table with 5 read and 5 write capacity units by default.
    • E. AWS::Serverless::SimpleTable supports only a single-attribute primary key.
Answers
  1. D. OpenApiVersion stops SAM from creating its default Stage stage, and Globals reaches the implicit API in one place. A is manual and repeats on every deployment; B changes the API type and its features; C adds a resource and edits every event, and SAM still creates Stage unless OpenApiVersion is set.
  2. C, E. SimpleTable has a single-attribute key, so a composite key and an index need AWS::DynamoDB::Table, which SAM templates accept like any CloudFormation resource. A is not supported; B is false; D is false because a SimpleTable without ProvisionedThroughput uses PAY_PER_REQUEST.

4. The Globals section

Concept

Exam facts

Developer angle

Globals:
  Function:
    Runtime: python3.13
    Timeout: 15
    Tracing: Active
    Environment:
      Variables:
        STAGE: prod
        TABLE_NAME: orders
    Layers:
      - !Sub 'arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:layer:shared-libs:3'
  Api:
    OpenApiVersion: '3.0.1'
Resources:
  ReportFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/report/
      Handler: app.handler
      Timeout: 60                  # primitive: replaces 15
      Environment:
        Variables:
          TABLE_NAME: reports      # map: overrides this key only
          FORMAT: csv              # map: added next to STAGE
      Layers:                      # list: result is [shared-libs:3, pdf-libs:7]
        - !Sub 'arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:layer:pdf-libs:7'

Effective configuration of ReportFunction: runtime python3.13, timeout 60 s, tracing Active, variables STAGE=prod, TABLE_NAME=reports, FORMAT=csv, layers shared-libs:3 then pdf-libs:7.

Traps

Practice questions

  1. A developer's template sets Layers: [!Ref LoggingLayer] under Globals → Function, and one function declares Layers: [!Ref ImageLayer]. Which layers does that function get after deployment, and in which order?

    • A. Only ImageLayer.
    • B. LoggingLayer, then ImageLayer.
    • C. ImageLayer, then LoggingLayer.
    • D. None, because the template fails validation with a duplicate property.
  2. A platform team moves shared settings of 30 functions into Globals to shorten the template. Which TWO settings must stay on each function resource? (Select TWO.)

    • A. Timeout
    • B. Policies
    • C. Tracing
    • D. Events
    • E. Environment
Answers
  1. B. Lists are additive and the global entries come first. A describes replacement, which applies to primitives only; C reverses the documented order; D is wrong because overriding is allowed.
  2. B, D. Policies and Events are not in the supported Globals property list. A, C and E are supported globals (Timeout is replaced and Environment merged when a function overrides them).

5. Permissions with policy templates and connectors

Concept

Exam facts

Template Placeholder Grants (summary)
S3ReadPolicy BucketName s3:GetObject, ListBucket, GetBucketLocation, GetObjectVersion, GetLifecycleConfiguration on the bucket and bucket/*
S3WritePolicy / S3CrudPolicy BucketName put objects (+ ACL, lifecycle) / read + write + delete objects
DynamoDBReadPolicy TableName GetItem, Scan, Query, BatchGetItem, DescribeTable on the table and table/<name>/index/*
DynamoDBCrudPolicy TableName read actions + PutItem, UpdateItem, DeleteItem, BatchWriteItem, ConditionCheckItem
DynamoDBWritePolicy TableName PutItem, UpdateItem, BatchWriteItem
DynamoDBStreamReadPolicy TableName, StreamName DescribeStream, GetRecords, GetShardIterator, ListStreams
SQSPollerPolicy QueueName ReceiveMessage, DeleteMessage(Batch), ChangeMessageVisibility(Batch), GetQueueAttributes
SQSSendMessagePolicy / SNSPublishMessagePolicy QueueName / TopicName sqs:SendMessage* / sns:Publish
LambdaInvokePolicy FunctionName lambda:InvokeFunction on the function (and its versions and aliases)
StepFunctionsExecutionPolicy / EventBridgePutEventsPolicy StateMachineName / EventBusName states:StartExecution / events:PutEvents on that bus
KMSDecryptPolicy KeyId kms:Decrypt; KeyId must be a key ID, not an alias
SSMParameterReadPolicy ParameterName GetParameter(s), GetParametersByPath; name without a leading slash (SSMParameterWithSlashPrefixReadPolicy for /a/b); non-default KMS key → add KMSDecryptPolicy
AWSSecretsManagerGetSecretValuePolicy SecretArn secretsmanager:GetSecretValue on that secret
KinesisStreamReadPolicy StreamName describe and read records of the stream
CloudWatchPutMetricPolicy, VPCAccessPolicy none → {} cloudwatch:PutMetricData / create, describe, detach and delete network interfaces

Developer angle

Resources:
  OrdersTable:
    Type: AWS::Serverless::SimpleTable
  OrdersQueue:
    Type: AWS::SQS::Queue
  OrdersFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/orders/
      Handler: app.handler
      Runtime: python3.13
      Policies:
        - DynamoDBCrudPolicy:               # template with a placeholder
            TableName: !Ref OrdersTable
        - SQSSendMessagePolicy:
            QueueName: !GetAtt OrdersQueue.QueueName
        - CloudWatchPutMetricPolicy: {}     # no placeholders: {} is mandatory
        - AWSXrayWriteOnlyAccess            # AWS managed policy by name
        - Version: '2012-10-17'             # inline policy document
          Statement:
            - Effect: Allow
              Action: ssm:GetParameter
              Resource: !Sub 'arn:${AWS::Partition}:ssm:${AWS::Region}:${AWS::AccountId}:parameter/orders/*'
  ReportFunction:
    Type: AWS::Serverless::Function
    Connectors:                              # SAM writes the read policy
      ReadOrders:                            # becomes ReportFunctionReadOrders
        Properties:
          Destination:
            Id: OrdersTable
          Permissions: [Read]
    Properties:
      CodeUri: src/report/
      Handler: app.handler
      Runtime: python3.13

Traps

Practice questions

  1. A developer's function polls a specific SQS queue with the SDK, processes the messages and deletes them. The team wants least privilege with the LEAST effort. Which Policies entry should the developer add?

    • A. The AWS managed policy AmazonSQSFullAccess
    • B. SQSSendMessagePolicy with QueueName: !GetAtt JobsQueue.QueueName
    • C. SQSPollerPolicy with QueueName: !GetAtt JobsQueue.QueueName
    • D. An inline policy that allows sqs:* on *
  2. A developer runs sam build, which fails with Must specify valid parameter values for policy template 'CloudWatchPutMetricPolicy'. The same function also declares KMSDecryptPolicy with KeyId: alias/payments, and the security team requires access to that key only. Which TWO changes are needed? (Select TWO.)

    • A. Declare the metric template as - CloudWatchPutMetricPolicy: {}.
    • B. Deploy with CAPABILITY_AUTO_EXPAND.
    • C. Move the Policies list into Globals.
    • D. Replace the templates with the AWS managed policy PowerUserAccess.
    • E. Pass the key ID of the payments key, not its alias, to KMSDecryptPolicy.
Answers
  1. C. SQSPollerPolicy grants exactly receive, delete, change visibility and get attributes on the named queue. A and D work but are far broader than needed; B only allows sending.
  2. A, E. Templates without placeholders still need an empty map, and KMSDecryptPolicy builds a key ARN from a key ID, so an alias doesn't match. B is unrelated to policy expansion; C is not supported; D breaks least privilege.

6. Creating and building projects with sam init and sam build

Concept

Exam facts

Developer angle

sam init --no-interactive --name orders-api --runtime python3.13 \
  --dependency-manager pip --app-template hello-world --architecture arm64
cd orders-api
sam validate --lint
sam build --cached --parallel        # writes .aws-sam/build and .aws-sam/build/template.yaml
sam build --use-container            # compiled dependencies built in a Lambda-like container
sam build OrdersFunction             # one resource only

An esbuild build declared in the template (image functions use Metadata → Dockerfile, DockerContext, DockerTag instead):

Resources:
  CheckoutFunction:                   # TypeScript bundled with esbuild
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/checkout/
      Handler: app.handler
      Runtime: nodejs22.x
    Metadata:
      BuildMethod: esbuild
      BuildProperties:
        Target: es2022                # default es2020; Minify defaults to true
        EntryPoints: [app.ts]

Traps

Practice questions

  1. A developer's Python function depends on a library with compiled C extensions. Built on the developer's macOS laptop, it passes the unit tests there but fails with import errors after deployment. Which change fixes the problem with the LEAST effort?

    • A. Change the function's Architectures to arm64.
    • B. Increase the function's MemorySize to 2048 MB.
    • C. Run sam deploy --force-upload.
    • D. Run sam build --use-container before deploying.
  2. A CI job builds a SAM application with 20 functions, and most commits change only one of them. The team wants faster builds without changing the deployment method. Which TWO options should the job add to sam build? (Select TWO.)

    • A. --use-container
    • B. --cached
    • C. --parallel
    • D. --debug
    • E. --build-image public.ecr.aws/sam/build-python3.13
Answers
  1. D. Building inside a Lambda-like container compiles the extensions for the Lambda environment. A changes the target architecture but not how dependencies are built; B does not fix missing or incompatible binaries; C re-uploads the same broken artifacts.
  2. B, C. Caching skips unchanged functions and parallel builds use more cores. A adds container start-up time; D only adds logging; E only chooses another build image and requires --use-container.

7. Packaging and deploying with sam package and sam deploy

Concept

Exam facts

Developer angle

# First deployment: answer the prompts once and save them to samconfig.toml
sam deploy --guided
# Repeatable, non-interactive deployment (CI)
sam build
sam deploy --stack-name orders-prod --resolve-s3 \
  --capabilities CAPABILITY_IAM \
  --parameter-overrides ParameterKey=Stage,ParameterValue=prod \
  --no-confirm-changeset --no-fail-on-empty-changeset
# Review first: create the change set and exit
sam deploy --stack-name orders-prod --resolve-s3 --capabilities CAPABILITY_IAM --no-execute-changeset
# Two-step flow when the packaged template is a pipeline artifact
sam package --s3-bucket my-artifacts-bucket --output-template-file packaged.yaml
sam deploy --template-file packaged.yaml --stack-name orders-prod --capabilities CAPABILITY_IAM
sam list stack-outputs --stack-name orders-prod
sam delete --stack-name orders-dev --no-prompts

Traps

Practice questions

  1. A CI job runs sam build and sam deploy --no-confirm-changeset on every commit. Commits that change only the README make the job fail although the stack is healthy. Which change fixes the job?

    • A. Add --force-upload to the sam deploy command.
    • B. Add --no-fail-on-empty-changeset to the sam deploy command.
    • C. Add --disable-rollback to the sam deploy command.
    • D. Replace the sam deploy step with sam package and keep the packaged template as an artifact.
  2. A team's CI job deploys a SAM application that contains .zip functions and container-image functions. The job must run without prompts, and the team doesn't want to pre-create an S3 bucket or ECR repositories for the artifacts. Which TWO options should the job pass to sam deploy? (Select TWO.)

    • A. --guided
    • B. --resolve-s3
    • C. --s3-bucket together with --resolve-s3
    • D. --force-upload
    • E. --resolve-image-repos
Answers
  1. B. By default sam deploy exits with an error when the change set is empty; the flag turns that into success. A re-uploads artifacts but still produces an empty change set; C changes failure behaviour, not the exit code; D stops deploying altogether.
  2. B, E. --resolve-s3 uses a SAM-managed bucket and --resolve-image-repos creates the ECR repositories for image functions, both without prompts. A is interactive and ignores both --resolve-* flags; C is an error because the two bucket options are mutually exclusive; D only re-uploads artifacts that already exist.

8. Configuration files and multiple environments

Concept

Exam facts

Developer angle

samconfig.toml with a development default and a production environment:

version = 0.1
[default.global.parameters]
stack_name = "orders-dev"
region = "eu-west-1"
[default.build.parameters]
cached = true
parallel = true
[default.deploy.parameters]
capabilities = "CAPABILITY_IAM"
confirm_changeset = true
resolve_s3 = true
parameter_overrides = "Stage=\"dev\" LogLevel=\"DEBUG\""
[prod.deploy.parameters]
stack_name = "orders-prod"
region = "eu-west-1"
capabilities = "CAPABILITY_IAM"
confirm_changeset = false
resolve_s3 = true
parameter_overrides = "Stage=\"prod\" LogLevel=\"WARN\""
sam deploy                                   # [default] sections
sam deploy --config-env prod                 # [prod.*] sections
# Command-line --parameter-overrides take precedence over parameter_overrides in the file
sam deploy --config-env prod \
  --parameter-overrides ParameterKey=Stage,ParameterValue=prod ParameterKey=LogLevel,ParameterValue=INFO
sam pipeline bootstrap --stage dev --permissions-provider oidc --oidc-provider github-actions
sam pipeline init                            # pick CodePipeline, GitHub Actions, GitLab, Jenkins or Bitbucket

In the template, the Stage parameter drives per-environment behaviour through a condition, for example IsProd: !Equals [!Ref Stage, prod] and MemorySize: !If [IsProd, 1024, 256] (conditions and intrinsic functions: notes/cloudformation-guide.md).

Traps

Practice questions

  1. A team deploys one SAM template to a development stack and a production stack with different stack names and parameter values. Developers keep typing long sam deploy commands and occasionally deploy development values to production. Which solution reduces the mistakes with the LEAST effort?

    • A. Define dev and prod environments in samconfig.toml and pass --config-env to sam deploy.
    • B. Copy the template into template-dev.yaml and template-prod.yaml with the values hard-coded in each copy.
    • C. Add a Mappings section keyed by account ID and remove all template parameters.
    • D. Run sam deploy --guided before every deployment and retype the values each time.
  2. A developer keeps samconfig.toml next to template.yaml, sets stack_name in both its global and deploy sections, and sometimes passes options on the command line. Which TWO statements describe how the SAM CLI resolves these settings? (Select TWO.)

    • A. An option given on the command line overrides the same option in samconfig.toml.
    • B. A template parameter's Default overrides values passed in parameter_overrides.
    • C. When both exist, samconfig.yaml is read before samconfig.toml.
    • D. For sam deploy, stack_name under [default.deploy.parameters] overrides stack_name under [default.global.parameters].
    • E. --config-file paths are resolved relative to the folder the command runs from.
Answers
  1. A. Named environments keep each stage's values in one file and turn the choice into one flag. B duplicates the template and drifts; C removes deploy-time flexibility and still needs per-account values; D keeps the error-prone typing.
  2. A, D. The CLI beats the file, and a command-specific section beats global. B is reversed (overrides beat defaults); C is reversed (samconfig.toml is looked up first); E is wrong because the path is relative to the template.

9. SAM Accelerate and testing in the cloud

Concept

Exam facts

Developer angle

# Development loop against a dev stack
sam sync --stack-name orders-dev --watch
# Push one function's code only (seconds, no CloudFormation)
sam sync --stack-name orders-dev --code --resource-id OrdersFunction
# All functions' code, but no APIs or state machines
sam sync --stack-name orders-dev --code --resource AWS::Serverless::Function
# Test what is deployed
sam remote invoke OrdersFunction --stack-name orders-dev --event-file events/order.json
sam remote invoke JobsQueue --stack-name orders-dev --event '{"jobId": "42"}'
sam logs --stack-name orders-dev --name OrdersFunction --tail --filter ERROR

Traps

Practice questions

  1. A developer iterates on a function's handler code in a development stack and wants every saved change to run in the AWS account within seconds, without typing a deploy command each time. Which command should the developer use?

    • A. sam deploy --no-confirm-changeset after every save
    • B. sam local start-api --warm-containers EAGER
    • C. sam sync --stack-name orders-dev --watch
    • D. sam build --cached --parallel
  2. A developer has used sam sync --code against a development stack for a week. The CloudFormation stack no longer matches the deployed function code, and a new IAM permission added to the template never took effect. Which TWO statements are correct? (Select TWO.)

    • A. --code updates IAM roles together with the function code.
    • B. --code updates code through service APIs and bypasses CloudFormation, which causes drift.
    • C. Enabling termination protection on the stack applies the pending permission.
    • D. Adding --no-dependency-layer makes --code apply IAM changes.
    • E. Running sam deploy (or sam sync without --code) applies the template's infrastructure changes.
Answers
  1. C. --watch keeps the CLI running and syncs code changes through service APIs in seconds. A works but needs a full change-set deployment per save; B runs locally, not in the account; D only builds.
  2. B, E. Code syncs bypass CloudFormation, so only a CloudFormation deployment applies the permission. A is false; C only blocks deletion; D only changes how dependencies are packaged.

10. Local testing with sam local and generated events

Concept

Exam facts

Developer angle

# S3 event for a specific bucket and key, piped straight into the function
sam local generate-event s3 put --bucket uploads-dev --key photos/cat.jpg \
  | sam local invoke ThumbnailFunction -e -
# Keep a reusable event and override environment variables
sam local generate-event apigateway http-api-proxy > events/http.json
sam local invoke CreateOrderFunction -e events/http.json --env-vars env.json --profile dev
# Local API and a local Lambda endpoint for SDK tests
sam local start-api --port 3000 --warm-containers EAGER
sam local start-lambda --port 3001
aws lambda invoke --function-name CreateOrderFunction \
  --endpoint-url http://127.0.0.1:3001 --no-verify-ssl out.json

env.json (global values plus a per-function override, which wins for that function):

{"Parameters": {"STAGE": "local", "TABLE_NAME": "orders-dev"},
 "CreateOrderFunction": {"TABLE_NAME": "orders-local-test"}}

In SDK-based tests, create the Lambda client with endpoint_url="http://127.0.0.1:3001" (AWS's boto3 example also disables SSL, request signing and retries) and call invoke as usual.

Traps

Practice questions

  1. A developer wants to test locally how a function handles an S3 upload notification for a specific bucket and object key, without uploading anything to AWS. Which approach requires the LEAST effort?

    • A. Upload a test object to the development bucket and then read the function's logs with sam logs --tail.
    • B. Run sam local start-api and send the object to the local endpoint with an HTTP POST request.
    • C. Run sam remote invoke ThumbnailFunction with an empty event.
    • D. sam local generate-event s3 put --bucket uploads-dev --key photos/cat.jpg | sam local invoke ThumbnailFunction -e -
  2. A CI job must run integration tests that call the Lambda Invoke API through the AWS SDK against functions running locally, before anything is deployed. Which TWO steps are required? (Select TWO.)

    • A. Start sam local start-lambda in the job.
    • B. Start sam local start-api and send the SDK calls to port 3000.
    • C. Point the SDK's Lambda client endpoint to http://127.0.0.1:3001.
    • D. Deploy the stack with sam sync before the tests run.
    • E. Set the AWS_LAMBDA_FUNCTION_NAME environment variable in the test process.
Answers
  1. D. generate-event builds a realistic S3 payload with the given bucket and key, and -e - feeds it to the local invocation. A and C run in the cloud; B serves API routes, not S3 notifications.
  2. A, C. start-lambda exposes a local Invoke endpoint (default port 3001), and the SDK client must target it. B emulates API Gateway routes, not the Lambda API; D deploys, which the requirement excludes; E is a variable that the Lambda runtime sets inside functions and does not redirect SDK calls.

11. Automatic versions and aliases with AutoPublishAlias

Concept

Exam facts

Developer angle

Parameters:
  LogLevel:
    Type: String
    Default: INFO
Resources:
  OrdersFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/orders/
      Handler: app.handler
      Runtime: python3.13
      AutoPublishAlias: live
      AutoPublishAliasAllProperties: true     # a Timeout change also publishes a version
      ProvisionedConcurrencyConfig:
        ProvisionedConcurrentExecutions: 5    # configured on the live alias
      Environment:
        Variables:
          LOG_LEVEL: !Ref LogLevel            # parameter-only changes: see the trap below
Outputs:
  LiveAliasArn:
    Value: !Ref OrdersFunction.Alias
  CurrentVersionArn:
    Value: !Ref OrdersFunction.Version

Check what is live with aws lambda get-alias --function-name <physical-name> --name live and aws lambda list-versions-by-function --function-name <physical-name>.

Traps

Practice questions

  1. A team's function sets AutoPublishAlias: live, and its LOG_LEVEL environment variable is !Ref LogLevel. When the team deploys with a new LogLevel value, the live alias keeps serving the old setting. Which change fixes this with the LEAST effort?

    • A. Set AutoPublishAliasAllProperties: true on the function.
    • B. Add AWS::LanguageExtensions before the serverless transform in Transform.
    • C. Delete the live alias before each deployment and let the next deployment recreate it.
    • D. Deploy with sam deploy --force-upload.
  2. A developer needs provisioned concurrency on the version of a function that receives production traffic, and the function URL must always reach the released version, not $LATEST. Which TWO template settings meet these requirements? (Select TWO.)

    • A. Set ProvisionedConcurrencyConfig on $LATEST without an alias.
    • B. Set ReservedConcurrentExecutions to pre-warm execution environments.
    • C. Set FunctionUrlConfig with InvokeMode: RESPONSE_STREAM.
    • D. Set AutoPublishAlias on the function.
    • E. Set ProvisionedConcurrencyConfig on the function, which SAM applies to the alias.
Answers
  1. B. With language extensions, references resolve before SAM computes the version hash, so the parameter change publishes a version and moves the alias. A doesn't help: parameter-only changes don't publish even with that flag; C causes downtime and is manual; D re-uploads artifacts but leaves the template unchanged.
  2. D, E. The alias exists only with AutoPublishAlias; provisioned concurrency is then set on it, and the function URL follows the alias. A is rejected (and $LATEST can't have provisioned concurrency); B caps or reserves capacity but doesn't pre-initialize; C changes the response mode, not the target version.

12. Traffic shifting with DeploymentPreference hooks and alarms

Concept

Exam facts

Developer angle

Resources:
  OrdersFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/orders/
      Handler: app.handler
      Runtime: python3.13
      AutoPublishAlias: live
      DeploymentPreference:
        Type: Canary10Percent5Minutes
        Alarms:
          - !Ref OrdersErrorsAlarm
        Hooks:
          PreTraffic: !Ref PreTrafficHook    # a PostTraffic hook follows the same pattern
  OrdersErrorsAlarm:
    Type: AWS::CloudWatch::Alarm
    Properties:
      Namespace: AWS/Lambda
      MetricName: Errors
      Dimensions: [{Name: FunctionName, Value: !Ref OrdersFunction}]
      Statistic: Sum
      Period: 60
      EvaluationPeriods: 1
      Threshold: 0
      ComparisonOperator: GreaterThanThreshold
      TreatMissingData: notBreaching
  PreTrafficHook:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: CodeDeployHook_ordersPreTraffic     # prefix required by the generated service role
      CodeUri: src/hooks/
      Handler: pre_traffic.handler
      Runtime: python3.13
      Timeout: 300
      Environment:
        Variables:
          TARGET_VERSION_ARN: !Ref OrdersFunction.Version
      Policies:
        - Version: '2012-10-17'
          Statement:
            - Effect: Allow
              Action: codedeploy:PutLifecycleEventHookExecutionStatus
              Resource: !Sub 'arn:${AWS::Partition}:codedeploy:${AWS::Region}:${AWS::AccountId}:deploymentgroup:${ServerlessDeploymentApplication}/*'
        - LambdaInvokePolicy:
            FunctionName: !Ref OrdersFunction

The hook tests the new version, then reports the result (no report within 1 hour = failed deployment):

import os
import boto3

codedeploy = boto3.client("codedeploy")
lambda_client = boto3.client("lambda")

def handler(event, context):
    result = lambda_client.invoke(FunctionName=os.environ["TARGET_VERSION_ARN"], Payload=b'{"healthCheck": true}')
    status = "Failed" if result.get("FunctionError") else "Succeeded"
    codedeploy.put_lifecycle_event_hook_execution_status(
        deploymentId=event["DeploymentId"],
        lifecycleEventHookExecutionId=event["LifecycleEventHookExecutionId"],
        status=status,
    )

Traps

Practice questions

  1. A team wants each release of a function to receive 10 % of production traffic for 5 minutes and then all traffic, with automatic rollback if the function's error alarm fires. Which solution requires the LEAST operational overhead?

    • A. Set AutoPublishAlias and a DeploymentPreference with Type: Canary10Percent5Minutes and the alarm under Alarms.
    • B. Set AutoPublishAlias and a DeploymentPreference with Type: Linear10PercentEvery1Minute and the alarm under Alarms.
    • C. Configure a canary on the API Gateway stage with 10 % of traffic and promote it after 5 minutes.
    • D. Run a scheduled script that calls aws lambda update-alias with a routing configuration and checks the alarm.
  2. A team's gradual deployments of a function keep failing about one hour after they start. The pre-traffic hook function's logs show that all its tests passed. Which TWO actions fix the problem? (Select TWO.)

    • A. Raise the hook function's timeout to 15 minutes.
    • B. Make the hook call PutLifecycleEventHookExecutionStatus with the DeploymentId and LifecycleEventHookExecutionId from its event.
    • C. Grant the hook's execution role codedeploy:PutLifecycleEventHookExecutionStatus.
    • D. Change the deployment Type to AllAtOnce.
    • E. Deploy the stack with CAPABILITY_AUTO_EXPAND.
Answers
  1. A. The predefined canary shifts 10 %, waits 5 minutes, shifts the rest, and rolls back on alarm. B shifts 10 % per minute (ten steps), not 10 % then everything; C splits API stage traffic and needs manual promotion; D is custom code to build and run.
  2. B, C. CodeDeploy waits for the hook's status report and fails the deployment after an hour without one; the hook must make the call and be allowed to. A doesn't send a status; D still runs the hooks; E is unrelated to hooks.

13. Serverless Application Repository and nested applications

Concept

Exam facts

Developer angle

Publisher side:

Metadata:
  AWS::ServerlessRepo::Application:
    Name: image-resizer
    Description: Resizes images uploaded to S3
    Author: platform-team
    SpdxLicenseId: Apache-2.0
    LicenseUrl: LICENSE.txt              # needed (with SemanticVersion) to go public
    ReadmeUrl: README.md
    Labels: ['images', 's3']
    SemanticVersion: 1.2.0
    SourceCodeUrl: https://github.com/example/image-resizer
sam package --s3-bucket sar-artifacts-bucket --output-template-file packaged.yaml
sam publish --template packaged.yaml --region eu-west-1
# Share with every account in the organization (keep the right to unshare)
aws serverlessrepo put-application-policy --region eu-west-1 \
  --application-id arn:aws:serverlessrepo:eu-west-1:111122223333:applications/image-resizer \
  --statements Principals=*,PrincipalOrgIDs=o-a1b2c3d4e5,Actions=Deploy,UnshareApplication

Consumer side, nesting the shared application:

Resources:
  Resizer:
    Type: AWS::Serverless::Application
    Properties:
      Location:
        ApplicationId: arn:aws:serverlessrepo:eu-west-1:111122223333:applications/image-resizer
        SemanticVersion: 1.2.0
      Parameters:
        MaxWidth: '1024'
Outputs:
  ResizerQueueUrl:
    Value: !GetAtt Resizer.Outputs.QueueUrl
sam deploy --stack-name media-prod --resolve-s3 --capabilities CAPABILITY_IAM CAPABILITY_AUTO_EXPAND
# Or deploy the application on its own through SAR: create the change set, then execute it
CHANGE_SET_ID=$(aws serverlessrepo create-cloud-formation-change-set \
  --application-id arn:aws:serverlessrepo:eu-west-1:111122223333:applications/image-resizer \
  --semantic-version 1.2.0 --stack-name image-resizer \
  --capabilities CAPABILITY_IAM CAPABILITY_RESOURCE_POLICY \
  --query ChangeSetId --output text)
aws cloudformation execute-change-set --change-set-name "$CHANGE_SET_ID"

Traps

Practice questions

  1. A company wants every account in its AWS Organization, and no one else, to deploy an internal application published in the Serverless Application Repository. Which solution meets the requirement with the LEAST effort?

    • A. Make the application public and tell the teams its name.
    • B. Add a bucket policy that allows the Organization to read the packaged artifacts in S3.
    • C. Call put-application-policy with the organization ID in PrincipalOrgIDs and Actions=Deploy,UnshareApplication.
    • D. Call put-application-policy separately for every member account, each time with that account's ID as the principal.
  2. A consumer calls aws serverlessrepo create-cloud-formation-change-set for a shared application. Its requiredCapabilities show that the template creates AWS::Lambda::Permission resources and contains a nested application but no IAM resources, and the call is rejected because those capabilities were not acknowledged. Which TWO changes let the deployment proceed? (Select TWO.)

    • A. Add CAPABILITY_RESOURCE_POLICY to --capabilities.
    • B. Add CAPABILITY_NAMED_IAM to --capabilities.
    • C. Retry the deployment with aws cloudformation deploy --disable-rollback.
    • D. Add CAPABILITY_AUTO_EXPAND to --capabilities.
    • E. Ask the publisher to add a bucket policy that grants serverlessrepo.amazonaws.com read access.
Answers
  1. C. An application policy with the Organization ID shares with all member accounts at once (and must include UnshareApplication). A exposes it to everyone; B doesn't grant deploy permission on the application; D works but must be repeated for every current and future account.
  2. A, D. Lambda permissions are resource policies (CAPABILITY_RESOURCE_POLICY) and nested applications need CAPABILITY_AUTO_EXPAND. B covers IAM resources with custom names, which this template doesn't create; C changes failure handling and acknowledges nothing; E is a publisher-side publishing requirement.

Quick decision rules

Templates, resources and permissions (§1–§5)

Build, deploy, configure and test (§6–§10)

Releases and sharing (§11–§13)

Changed vs older material

Learn the Current column; older practice material may still show the Older material may say value. These rows will move to notes/current-facts.md once you confirm them during /ingest.

Topic Older material may say Current (verified 2026-10-12) Source
§1 · Template format All SAM configuration is YAML SAM templates can be YAML or JSON AWS docs
§1 · SAM resource types Only Function, Api and SimpleTable (or the original seven types) 13 types: Api, Application, CapacityProvider, Connector, Function, GraphQLApi, HttpApi, LayerVersion, MicrovmImage, NetworkConnector, SimpleTable, StateMachine, WebSocketApi AWS docs
§2 · Scheduled functions Use the Schedule event (EventBridge / CloudWatch Events rule) AWS recommends ScheduleV2 (EventBridge Scheduler); Schedule still creates an AWS::Events::Rule AWS docs
§4 · Globals resource types Function, Api, HttpApi, SimpleTable 8 types: those plus StateMachine, CapacityProvider, MicrovmImage, NetworkConnector (the anatomy page lists six) AWS docs
§7 · Packaging before deployment sam package must run before sam deploy sam deploy packages implicitly; sam package is optional (packaged template as an artifact) AWS docs
§10 · Local emulation scope SAM runs Lambda, API Gateway and DynamoDB locally SAM CLI emulates Lambda and API Gateway; DynamoDB needs DynamoDB local (JAR, Docker image or Maven) or a real table AWS docs · SAM testing
§10 · sam local start-api reloads Changes to functions are always reloaded automatically Automatic only without an .aws-sam build (interpreted runtimes); after sam build, rebuild to pick up changes; template changes need a restart AWS docs