Infrastructure as Code

SAM과 Serverless Framework

meellon 2026. 7. 19. 18:50

학습 목표

SAM template.yamlTransform·AWS::Serverless::* 리소스를 읽고 작성할 수 있다.

sam build·sam deploy·sam local invoke로컬 검증 후 배포 흐름을 실행할 수 있다.

Globals·Events로 Lambda·API를 선언적으로 묶는 패턴을 설명할 수 있다.

Serverless Framework serverless.yml과 SAM·CDK의 차이·선택을 말할 수 있다.

11편 Lambda·API Gateway 스택을 SAM으로 동일 워크로드 표현할 수 있다.

문제 상황

  • 11편 CDK로 API·Lambda는 썼지만 — YAML만 쓰는 팀·튜토리얼은 SAM
  • template.yamlAWS::Serverless::Function — 일반 CFn과 뭐가 다른지 모름
  • sam build 없이 deploy — CodeUri 경로·의존성 깨짐
  • 로컬에서 handler 테스트 없이 deploy — event JSON 형식 틀려서 500
  • Serverless Framework 예제는 많은데 — SAM·CDK와 언제 고르는지 없음
  • 9편 cdk deploy bootstrap은 봤지만 — SAM artifact bucket·samconfig는 생소
  • 멀티 클라우드 plugin vs AWS 네이티브 — lock-in·운영 tradeoff 불명

11편에서 handler·IAM·HTTP API를 CDK로 봤다. 이번 편은 Lambda 특화 IaCSAMServerless Framework — 의 template·CLI·로컬 invoke다. SQS·EventBridge 이벤트 소스는 13편.

1. SAM이란?

AWS SAM(Serverless Application Model) — CloudFormation 위에 서버리스 리소스짧은 문법으로 쓰는 확장.

요소 역할
Transform AWS::Serverless-2016-10-31 — SAM 리소스를 CFn으로 확장
AWS::Serverless::Function Lambda + IAM + (선택) event 한 블록
AWS::Serverless::HttpApi HTTP API v2 간소 정의
Globals Function·Api에 공통 runtime·timeout·env
Outputs 배포 후 URL·ARN 노출
# code/template.example.yaml (발췌)
Transform: AWS::Serverless-2016-10-31

Globals:
  Function:
    Runtime: nodejs20.x
    Timeout: 10

Resources:
  HttpApiHandler:
    Type: AWS::Serverless::Function
    Properties:
      Handler: handler.handler
      CodeUri: src/
      Events:
        Health:
          Type: HttpApi
          Properties:
            Path: /health
            Method: GET
  • 결과sam build확장된 CFn template (6편 synthesis와 유사)
  • AWS 전용 — Lambda·API GW·DynamoDB 패턴에 최적
  • CDKaws-sam construct 또는 CFn import로 공존 가능

2. template 구조 — Globals · Events

SAM은 이벤트 소스를 Function 안에 선언한다.

섹션 용도
Globals 모든 Function·Api 기본값
Resources Function·HttpApi·Table …
Events API·SQS·S3·Schedule 트리거 (Function 하위)
Policies SAM policy template — DynamoDBReadPolicy
Outputs sam deploy스택 출력
  • Events.HttpApi — 11편 HttpLambdaIntegration + route 축약
  • CodeUri — 소스 디렉터리·zip — build 시 artifact 생성
  • MetadataBuildMethod: esbuild번들 옵션
  • Parameters — stage·env 분리 (5편 tfvars 패턴)

3. sam build — artifact 준비

sam build — 의존성 설치·번들·.aws-sam/build배포 가능 artifact 생성.

단계 내용
Resolve template.yaml 파싱·Transform
Build CodeUrinpm install·esbuild 등
Output .aws-sam/build/template.yaml경로 치환된 CFn
Cache 변경 없는 함수 스킵 (옵션)
sam validate --lint
sam build
# .aws-sam/build/HttpApiHandler/  ← 배포 zip
  • build 없이 deploy — 구버전 코드·누락 node_modules 배포
  • Layer — 별도 빌드·ContentUri
  • Container imagePackageType: Image — Docker build
  • 9편 CDK asset publish와 동일 역할 — bootstrap bucket 사용

4. deploy · local invoke

로컬에서 event JSON으로 handler 검증 후 스택 배포.

# code/sam-workflow.sh (발췌)
sam build
sam local invoke HttpApiHandler --event events/health-get.json
sam deploy --guided   # samconfig.toml 생성
명령 역할
sam local invoke Docker로 런타임 재현·event 주입
sam local start-api 로컬 API 엔드포인트 (통합 테스트)
sam deploy CFn stack create/update
sam delete 스택 삭제
--guided stack name·region·capabilities 최초 설정
// code/events/health-get.json (발췌)
{
  "requestContext": { "http": { "method": "GET" } },
  "rawPath": "/health"
}
  • event fixture — 11편 APIGatewayProxyEventV2 형식 재사용
  • samconfig.toml — env별 parameter (5편 workspace 개념)
  • CIsam build + sam deploy --no-confirm-changeset (9편 CDK CI)
  • Changeset — CFn 승인 — prod 수동 gate

5. Serverless Framework

Serverless Frameworkserverless.yml + plugin으로 멀티 클라우드·로컬 DX.

# code/serverless.example.yml (발췌)
service: items-api
provider:
  name: aws
  runtime: nodejs20.x
functions:
  httpApiHandler:
    handler: src/handler.handler
    events:
      - httpApi:
          path: /health
          method: get
  SAM Serverless Framework CDK
형식 CFn YAML + Transform serverless.yml TypeScript·Python
엔진 CloudFormation plugin → CFn/Terraform CloudFormation
로컬 sam local serverless offline 없음 (unit test)
AWS 특화 네이티브 plugin 의존 L2 construct
멀티 클라우드 AWS only plugin AWS 주력
적합 AWS SAM·CFn 팀 빠른 MVP·plugin 생태계 대형·타입·테스트
  • 동일 handler — 11편 코드 재사용 — IaC 문법만 교체
  • Plugin — offline·esbuild·domain — 버전 고정 필수
  • 팀 표준 — 이미 CDK면 SAM 병행한 앱 단위로만
  • 13편 — SAM EventsSQS·EventBridge 추가

6. 실무 체크리스트

# 질문
1 sam build를 deploy 전에 항상 돌리는가
2 local invoke event가 HTTP API v2 형식인가
3 samconfig.toml·parameter로 env가 분리됐는가
4 SAM vs CDK 선택 이유가 팀에 문서화됐는가
5 Serverless plugin lockfile이 CI에 고정됐는가
6 IAM은 SAM policy template·최소 권한인가

정리

  • SAM — CFn Transform·AWS::Serverless::*·Globals·Events
  • sam build — artifact·확장 template — deploy 필수 전제
  • sam local invoke — event fixture로 배포 전 handler 검증
  • Serverless Framework — yml·plugin·offline — DX·생태계
  • CDK — 타입·테스트·대규모 — 같은 CFn 엔진과 공존
  • 13편 — 이벤트 기반 SQS·EventBridge

다음에 다룰 것

  • 이벤트 기반 Serverless
  • SQS, EventBridge, DynamoDB Streams, fan-out

해당 내용은 AWS SAM Developer Guide, Serverless Framework documentation 을 기반으로 합니다.

'Infrastructure as Code' 카테고리의 다른 글

Lambda와 API Gateway  (0) 2026.07.16
Serverless 아키텍처  (0) 2026.07.12
CDK 테스트와 배포  (0) 2026.07.10
CDK vs Terraform  (0) 2026.07.10
CDK로 인프라 정의  (0) 2026.07.09