# AWS - SAM


# SAM(Serverless Application Model)

SAM Serverless Application Model 是一套 serverless IaC 框架,擴充 Cloud Formation,讓編寫與部署 Serverless Services 更簡單

支援 Serverless 服務

  • Lambda
  • API Gateway
  • DynamoDB
  • SQS
  • EventBridge
  • Step Functions
  • SAM Pipelines(CI/CD)

# SAM 主要功能

  • sam build: 打包程式碼與依賴
  • sam local: 本地執行 Lambda/API (使用 Docker 模擬 Lambda Runtime)
  • sam deploy: 以 CloudFormation Template 形式部署到 AWS

# SAM Template Example

1
2
3
4
5
6
7
8
9
10
11
12
13
Transform: AWS::Serverless-2016-10-31
Resources:
HelloFunction:
Type: AWS::Serverless::Function
Properties:
Handler: app.lambda_handler
Runtime: python3.12
Events:
Api:
Type: Api
Properties:
Path: /hello
Method: get

AWS::Serverless::Function 自動轉成 CloudFormation + Lambda + API Gateway


# SAM 與 CloudFormation 關係

CloudFormation SAM
很多 YAML/JSON 更簡短,有很多預設
需要手動建立 Event Trigger 自動將事件與 Lambda 綁定
靈活但頻繁 Serverless 最佳化

SAM 是 CloudFormation 的抽象與增強


# SAM 指令


# SAM Init

  • sam init 建立新的 Serverless 專案 (模板可選 API/Event/HelloWorld 等)

# SAM Build

  • sam build: 打包 Lambda Function Code + Dependencies
  • sam build --use-container: 使用 Docker 模擬 Lambda Layer 打包

# SAM Local

  • sam local invoke: 本地執行單一 lambda
  • sam local start-api: 模擬 API Gateway
  • sam local start-lambda: 外部呼叫 lambda endpoint
  • sam local generate-event: 自動生成 Lambda 觸發事件範例 (S3/SQS/API 等 Payload)
  • sam logs: 抓 CloudWatch logs

開發迭代非常快
Docker 容器完整模擬 Lambda Runtime


# SAM Deploy

  • sam deploy --guided: 第一次部署,寫入參數為 defaults
  • sam deploy: 依照現有設定快速部署
  • sam sync: 熱部署,極快,進行 code-only 更新 (無需整套 CloudFormation)
  • sam delete: 刪除整套部署資源

sam sync 是近代最重要提升 > 適合快速開發 Lambda + API


# SAM Pipeline

  • sam pipeline init: 產生 CI/CD 工作流程 (Code Pipeline/GitHub Actions)
  • sam pipeline bootstrap: 初始化 pipeline 環境 (IAM/S3/ECR/KMS)
  • sam pipeline deploy: 透過 Pipeline 部署

# SAM Management

  • sam validate: 驗證 template 格式與資源設定
  • sam list: 列出服務與堆疊資訊
  • sam get: 下載範例資源
  • sam publish: 將 App 發佈到 SAR (Serverless App Repository)
  • sam traces: 查詢 X-Ray traces
  • sam accelerate: 與 sync 搭配改善 loop time

# CI/CD: SAM Pipeline

SAM 內建自動化

  • CodeBuild
  • CodePipeline
  • GitHub/GitLan
  • Gradually Deployment: Dev > Staging > Prod

適合團隊共同開發部署


# Obersevability

內建最佳化

  • AWS X-Ray
  • CloudWatch Logs + Metrics
  • Tracing
  • 統一 Log format (lambda Powertools)

# Reference

  • AWS - Introduction to testing with the sam local command
  • AWS - AWS SAM template anatomy
  • AWS - sam deploy
  • AWS - What is the AWS Serverless Application Model (AWS SAM)?
更新於