AWS SAM · Serverless Application Model

CloudFormation shorthand for serverless. One Transform: line turns a 20-line YAML file into the ~100 lines of raw CloudFormation you'd otherwise hand-write for a Lambda + API Gateway + DynamoDB app. It also gives you a CLI that runs those functions locally and a one-liner for canary traffic shifting.

Cách viết tắt CloudFormation cho serverless. Một dòng Transform: biến file YAML 20 dòng thành ~100 dòng CloudFormation thô mà bạn phải tự gõ cho app Lambda + API Gateway + DynamoDB. Kèm theo là CLI chạy các function đó cục bộ và một dòng để bật canary traffic shifting.

Reach for it / not the right toolKhi nào dùng / khi nào không

Reach for SAMChọn SAM

  • A Lambda-centric app — functions, an API, a table, a state machine — and you want the YAML to stay short.App xoay quanh Lambda — function, API, table, state machine — và muốn YAML ngắn gọn.
  • You need to invoke functions locally before deploying, with real event payloads.Cần chạy function cục bộ trước khi deploy, với event payload thật.
  • Canary / linear Lambda deployments with automatic rollback on a CloudWatch alarm, without hand-writing CodeDeploy resources.Deploy Lambda canary / linear tự rollback theo CloudWatch alarm, không phải tự viết resource CodeDeploy.
  • The team is comfortable in YAML and doesn't want a build toolchain in a programming language.Team quen YAML và không muốn thêm toolchain build bằng ngôn ngữ lập trình.

Not the right toolKhông phải chỗ dùng

  • Infrastructure that's mostly not serverless — VPCs, ECS clusters, RDS. SAM has no shorthand for those (though you can still declare them as plain CFN resources in the same file).Hạ tầng phần lớn không serverless — VPC, ECS cluster, RDS. SAM không có cú pháp tắt cho chúng (vẫn khai báo được như resource CFN thường trong cùng file).
  • You want loops, conditionals and types when authoring infra → CDK.Muốn vòng lặp, điều kiện và kiểu dữ liệu khi viết hạ tầng → CDK.
  • A curated self-service catalog for non-engineers → Service Catalog.Một catalog self-service cho người không phải kỹ sư → Service Catalog.

What actually happens on deployDeploy thực sự xảy ra chuyện gì

The mental model that answers most questions: SAM is a preprocessor. Your template gets expanded into ordinary CloudFormation before a single resource is created. Mô hình tư duy giải đáp hầu hết câu hỏi: SAM là một preprocessor. Template của bạn được nở thành CloudFormation thường trước khi bất kỳ resource nào được tạo.

A SAM template plus function code go through sam build and sam deploy, which upload artifacts to S3 and hand a template to CloudFormation; the AWS::Serverless transform expands it into a plain CloudFormation template, which then creates Lambda, API Gateway, DynamoDB and IAM roles. template.yaml Transform: AWS::Serverless SAM CLI sam build sam deploy S3 artifacts zipped code CloudFormation transform expands to a plain template Lambda + version + alias API Gateway + stage DynamoDB table IAM roles & permissions

Because the output is a plain stack, everything CloudFormation offers still works: change sets, drift detection, DeletionPolicy, nested stacks, StackSets. You can also mix raw AWS::* resources into the same template.

Vì đầu ra là stack thường, mọi thứ CloudFormation có vẫn dùng được: change set, drift detection, DeletionPolicy, nested stack, StackSets. Cũng có thể trộn resource AWS::* thô vào cùng template.

A whole app in one fileCả một app trong một file

Read this once and the syntax sticks. Note what's missing: no IAM role, no API Gateway method/integration/deployment, no Lambda permission resource — the transform generates all of it. Đọc một lần là nhớ cú pháp. Chú ý cái thiếu: không IAM role, không method/integration/deployment của API Gateway, không resource Lambda permission — transform sinh hết.

Transform: AWS::Serverless-2016-10-31   # the one required line

Globals:                                # applied to every function below
  Function:
    Runtime: python3.12
    Timeout: 10
    MemorySize: 512
    Tracing: Active                     # X-Ray on, no extra config

Resources:
  OrdersTable:
    Type: AWS::Serverless::SimpleTable  # → a DynamoDB table, on-demand
    Properties:
      PrimaryKey: { Name: orderId, Type: String }

  CreateOrderFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/create_order/        # a local folder; sam build packages it
      Handler: app.lambda_handler
      Policies:                         # policy templates, not raw JSON
        - DynamoDBCrudPolicy: { TableName: !Ref OrdersTable }
      Environment:
        Variables:
          TABLE_NAME: !Ref OrdersTable
      Events:                           # ← this creates the API Gateway
        Api:
          Type: HttpApi
          Properties: { Path: /orders, Method: POST }
Three things worth stealingBa thứ đáng nhớ Events — an event source (Api, S3, SQS, Schedule, DynamoDB stream…) declared on the function creates the trigger and the permission. Policies — named policy templates (DynamoDBCrudPolicy, S3ReadPolicy, SQSSendMessagePolicy) instead of hand-written IAM. Globals — defaults for every function/API in the file. Events — khai báo event source (Api, S3, SQS, Schedule, DynamoDB stream…) trên function sẽ tạo cả trigger lẫn permission. Policies — policy template có tên (DynamoDBCrudPolicy, S3ReadPolicy, SQSSendMessagePolicy) thay vì tự viết IAM. Globals — giá trị mặc định cho mọi function/API trong file.

Traffic shifting — SAM's one-liner for CodeDeployTraffic shifting — một dòng SAM gọi CodeDeploy

Add AutoPublishAlias + DeploymentPreference and SAM generates a Lambda version, an alias, a CodeDeploy application & deployment group, and the rollback wiring. This is the exam's favourite SAM detail. Thêm AutoPublishAlias + DeploymentPreference và SAM sinh ra version Lambda, một alias, một CodeDeploy application & deployment group, cùng dây rollback. Đây là chi tiết SAM hay ra thi nhất.

  CreateOrderFunction:
    Type: AWS::Serverless::Function
    Properties:
      AutoPublishAlias: live            # publish a new version, point "live" at it
      DeploymentPreference:
        Type: Canary10Percent5Minutes   # 10% for 5 min, then the remaining 90%
        Alarms:                         # any alarm firing → automatic rollback
          - !Ref ErrorRateAlarm
        Hooks:
          PreTraffic:  !Ref RunSmokeTestsFunction
          PostTraffic: !Ref RunIntegrationTestsFunction
Canary10PercentXMinutes 10% first, wait 5 / 10 / 15 / 30 min, then the rest at once10% trước, đợi 5 / 10 / 15 / 30 phút, rồi đẩy nốt phần còn lại
Linear10PercentEveryXMinutes +10% every 1 / 2 / 3 / 10 min until 100%+10% mỗi 1 / 2 / 3 / 10 phút tới 100%
AllAtOnce flip immediately — still gets alarm-based rollbackchuyển ngay — vẫn có rollback theo alarm
The one that bitesCái dễ dính Traffic shifting only works against a Lambda alias. If callers invoke the function by name or $LATEST instead of the alias ARN, every request goes to the new code immediately and the canary is decorative. Point API Gateway, EventBridge and SDK callers at the alias. Traffic shifting chỉ hoạt động trên alias Lambda. Nếu bên gọi dùng tên function hoặc $LATEST thay vì ARN alias, mọi request vào code mới ngay lập tức và canary chỉ để trang trí. Trỏ API Gateway, EventBridge và SDK vào alias.

See CodeDeploy for what the hooks and alarms mean in general; SAM just declares them for you. Xem CodeDeploy để hiểu hook và alarm nói chung; SAM chỉ khai báo hộ bạn.

CI/CD architecture for SAMKiến trúc CI/CD cho SAM

A pipeline: source repository, then CodeBuild builds tests and packages, then CloudFormation with SAM creates the stack, then CodeDeploy shifts traffic between Lambda version v1 and v2 via an alias; DynamoDB and API Gateway are created directly by the stack. CodePipeline Source repo git push CodeBuild build · test · package CloudFormation + SAM transform CodeDeploy shifts the alias Lambda v1 Lambda v2 "live" DynamoDB API Gateway

CodeBuild runs sam build && sam package; the stack creates every resource; CodeDeploy only handles the Lambda alias traffic shift. Everything else in the app is created directly by the stack.

CodeBuild chạy sam build && sam package; stack tạo mọi resource; CodeDeploy chỉ lo dịch traffic trên alias Lambda. Phần còn lại của app do stack tạo trực tiếp.

The CLI worth rememberingNhững lệnh CLI đáng nhớ

CommandLệnh What it doesLàm gì
sam init Scaffold a project from a runtime template.Dựng khung project từ template theo runtime.
sam build Resolve dependencies and produce deployable artifacts in .aws-sam/build — optionally inside the Lambda container image (--use-container) so native libs match.Giải phụ thuộc và tạo artifact deploy trong .aws-sam/build — có thể build trong image container Lambda (--use-container) để thư viện native khớp môi trường.
sam local invoke · start-api Run the function / a local API Gateway in Docker on your machine. Needs Docker; approximates but doesn't replace real IAM.Chạy function / một API Gateway cục bộ trong Docker trên máy bạn. Cần Docker; mô phỏng chứ không thay được IAM thật.
sam deploy --guided Upload to S3, create a change set, execute it. Answers are saved to samconfig.toml.Upload lên S3, tạo change set, thực thi. Câu trả lời được lưu vào samconfig.toml.
sam sync --watch SAM Accelerate — pushes code changes straight to Lambda in seconds instead of a full stack update. Dev environments only.SAM Accelerate — đẩy thay đổi code thẳng lên Lambda trong vài giây thay vì update cả stack. Chỉ dùng cho env dev.
sam logs · sam traces Tail CloudWatch Logs / fetch X-Ray traces for the deployed functions.Theo dõi CloudWatch Logs / lấy trace X-Ray của function đã deploy.

Exam reflexesPhản xạ khi thi

The question says…Đề nói… AnswerTrả lời
"Test the Lambda function locally before deploying""Test Lambda cục bộ trước khi deploy" SAM CLI — sam local invoke / start-apiSAM CLI — sam local invoke / start-api
"Shift 10% of traffic to the new Lambda and roll back on errors""Đẩy 10% traffic sang Lambda mới và rollback khi lỗi" SAM DeploymentPreference → CodeDeploy canary + alarmsSAM DeploymentPreference → CodeDeploy canary + alarm
"Minimise the YAML for a Lambda + API + table app""Giảm YAML cho app Lambda + API + table" SAM (not raw CloudFormation)SAM (không phải CloudFormation thô)
"Run smoke tests before production traffic reaches the new version""Chạy smoke test trước khi traffic production tới version mới" Hooks: PreTraffic LambdaLambda ở Hooks: PreTraffic
"Infra spans VPC, ECS and Lambda, written in TypeScript""Hạ tầng gồm VPC, ECS và Lambda, viết bằng TypeScript" CDK, not SAMCDK, không phải SAM