AWS SAM에 대해 알아보자 + 람다도 만들어보자

2022.03.25

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

안녕하세요, 임채정입니다.
이번 블로그에서는 서버리스 애플리케이션을 위한 프레임워크인 SAM 서비스에 대해서 알아보고 정리했습니다.
또한, 실제로 SAM을 사용해서 간단하게 람다 함수까지 만들어보겠습니다.

아젠다

  1. AWS SAM 의 정의
  2. AWS SAM 을 사용해보자

1. AWS SAM 의 정의

AWS SAM

  • Serverless Application Model (SAM)
  • AWS 환경에서 제공하는 서버리스 애플리케이션 구축용 오픈 소스 프레임워크
  • AWS CloudFormation이 확장된 형태로, 배포 과정에서 SAM Template이 CloudFormation Template으로 변환
  • 구축가능한 AWS 서비스의 종류
    • Lambda
    • API Gateway
    • DynamoDB

AWS SAM의 장점

  • AWS에서 서버리스 시스템을 구성할 때 필요한 CloudFormation 코드가 추상화되어 있어, 좀 더 직관적으로 서버리스를 구성할 수 있다
  • 기존의 CloudFormation 코드와 함께 사용이 가능하다
  • Local 환경에서 SAM 명령어를 통해 Lambda 함수를 테스트해 볼 수 있어 개발에 편리하고 번거로움을 대폭 줄일 수 있다

2. AWS SAM 을 사용해보자

2-1. SAM CLI 다운

먼저 SAM을 하기 위해서는 SAM CLI 를 다운받아야 합니다.
해당 공식 도큐먼트 사이트에서 자신이 사용하는 OS를 선택하고 순서대로 다운을 받으면 됩니다.

저는 mac을 사용하고 있기 때문에 mac 순서 페이지에 있는 명령어를 실행해서 SAM CLI 을 다운받겠습니다.

brew tap aws/tap
brew install aws-sam-cli

다운로드가 끝나면 버전을 확인해서 잘 다운로드 되었는지 확인합니다.

$ sam --version
SAM CLI, version 1.41.0

2-2. 새로운 Serverless 프로젝트 만들어보기

이제 새로운 SAM를 사용해서 간단한 람다를 하나 만들어보겠습니다.
먼저 코드 에디터를 하나 켜주고 (저는 Visual Studio Code를 사용했습니다)
다음 사진처럼 폴터와 파일을 생성합니다.

이때, 각각의 역할을 다음과 같습니다.

  • gener/ : cloudformation 패키지를 생성했을 때 template 으로 저장될 폴터
  • scr/app.py : 람다파일 안에 들어갈 코드 파일
  • template.yam : 생성한 람다의 template 파일
  • commands.sh : 실행할 명령어를 정리

그럼 각각의 파일을 간단하게 작성해주겠습니다.
scr/app.py

import json
  
print ('Loading function')
 
def  lambda_handler(event, context):
	return  "start SAM"

template.yam

AWSTemplateFormatVersion: "2010-09-09"
Transform: 'AWS::Serverless-2016-10-31'
Description: A Simple AWS Lambda function
  
# ------------
# Parameters
# ------------
Resources:
	lambdaPython3:
		Type: 'AWS::Serverless::Function'
		Properties:
			Handler: app.lambda_handler
			Runtime: python3.6
			CodeUri: src/
			Description: A Simple AWS Lambda function
			MemorySize: 128
			Timeout: 3

commands.sh : 실행할 명령어를 정리

# create s3 bucket
aws s3 mb s3://save-sam-code-202203
  
# package cloudformation
aws cloudformation package --s3-bucket save-sam-code-202203 --template-file template.yaml --output-template-file gener/template-generated.yaml
  
# deploy
aws cloudformation deploy --template-file gener/template-generated.yaml --stack-name simple-lambda-sam --capabilities CAPABILITY_IAM

2-3. 배포 하기

이번에는 실제로 배포하기 위해 commands.sh파일에 있는 명령어를 하나씩 실행해보겠습니다.

1) create s3 bucket
먼저 S3버킷을 만들어주겠습니다.
S3버킷의 생성 목적은 CloudFormation 패키지를 생성할 때 람다의 함수를 저장할 용도입니다.
해당 함수는 패키지화된 CloudFormation 템플릿에서 람다 함수의 코드를 가져올 때 사용됩니다.

aws s3 mb s3://save-sam-code-202203

# 결과
make_bucket: save-sam-code-202203

콘솔 화면에서 확인해봐도 성공적으로 작성이 되었습니다.

2) package cloudformation
다음으로는 cloudformation에서 실행할 수 있도록 템플릿과 람다함수코드를 패키지화 하겠습니다.

aws cloudformation package --s3-bucket save-sam-code-202203 --template-file template.yaml --output-template-file gener/template-generated.yaml

# 명령어 구조
aws cloudformation package --s3-bucket (버킷 이름) --template-file (리스소 템플릿 경로 및 이름) --output-template-file (패키지화된 템플릿 생성할 경로 및 파일 이름)

# 결과
Uploading to b0441067ed40a9c37e427e0ff110befd  201 / 201.0  (100.00%)
Successfully packaged artifacts and wrote output template to file gener/template-generated.yaml.
Execute the following command to deploy the packaged template
aws cloudformation deploy --template-file /Users/lim/Desktop/SAM/gener/template-generated.yaml --stack-name <YOUR STACK NAME>

결과를 확인해보면 S3에 파일이 생성되었고

설정한 경로에 성공적으로 새로운 파일이 작성되었습니다.
gener/template-generated.yaml

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: A Simple AWS Lambda function
Resources:
	lambdaPython3:
		Type: AWS::Serverless::Function
		Properties:
			Handler: app.lambda_handler
			Runtime: python3.6
			CodeUri: s3://save-sam-code-202203/b0441067ed40a9c37e427e0ff110befd
			Description: A Simple AWS Lambda function
			MemorySize: 128
			Timeout: 3

3) deploy
이제 배포를 하겠습니다.
템플릿을 cloudformation의 패키지화하기 위해 실행한 명령어의 결과에 다음에 실행할 명령어의 힌트가 있습니다.

Execute the following command to deploy the packaged template
aws cloudformation deploy --template-file /Users/lim/Desktop/SAM/gener/template-generated.yaml --stack-name <YOUR STACK NAME>

위의 힌트를 복사해서 실행할 명령어를 작성합니다.

aws cloudformation deploy --template-file gener/template-generated.yaml --stack-name simple-lambda-sam --capabilities CAPABILITY_IAM

# 명령어 구조
aws cloudformation deploy --template-file (실행한 템플릿의 경로 및 파일) --stack-name (생성할 Cfn의 스택이름) --capabilities CAPABILITY_IAM

# 결과
Waiting for changeset to be created..
Waiting for stack create/update to complete
Successfully created/updated stack - simple-lambda-sam

성공적으로 스택이 생성되었습니다.
콘솔 화면에서도 확인해보면 스택이 제대로 생성이 됐습니다.

또한, 람다 함수도 성공적으로 생성되었습니다.

람다 함수를 실행해도 잘 실행됩니다.

Response
"start SAM"

Function Logs
START RequestId: cfc68de5-8faf-499e-9477-f98c2c70a5ad Version: $LATEST
Loading function
END RequestId: cfc68de5-8faf-499e-9477-f98c2c70a5ad
REPORT RequestId: cfc68de5-8faf-499e-9477-f98c2c70a5ad	Duration: 1.44 ms	Billed Duration: 2 ms	Memory Size: 128 MB	Max Memory Used: 42 MB	Init Duration: 186.01 ms

여기까지 SAM을 사용해서 간단하게 람다 함수를 생성해봤습니다.

본 블로그 게시글을 보시고 문의 사항이 있으신 분들은 클래스메소드코리아 (info@classmethod.kr)로 연락 주시면 빠른 시일 내 담당자가 회신 드릴 수 있도록 하겠습니다 !