AWS SAM으로 API Gateway를 만들어 봤습니다.

2022.03.25

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

안녕하세요, 임채정입니다.
이번 블로그에서는 AWS SAM을 사용해서 API Gateway를 만들어보고 정리했습니다.

아젠다

  1. 사전 조건
  2. 코드 작성
  3. 실행

1. 사전 조건

SAM CLI가 실행할 환경에 다운로드 되어 있어야 합니다.
만약 해당 코드를 실행했을 때 다음과 같이 버전 정보가 나오지 않는다면 아래 사이트에 접속해서 자신의 OS에 맞는 페이지로 이동해서 SAM CLI 를 다운받아주시길 바랍니다.

$ sam --version
SAM CLI, version 1.41.0

SAM CLI 를 다운받는 법

2. 코드 작성

이제 SAM으로 실행을 해보기 전에 코드를 작성하도록 하겠습니다.
다음과 같이 폴터 및 파일을 생성합니다.

SAM
├─ gener
├─ scr
│  └─ app.py  
├─ commands.sh
└─ template.yaml

gener : 나중에 패키지화된 CloudFormation의 템플릿이 저장된 폴더입니다.

app.py : 생성할 람다 코드 내용
해당 람다는 API Gateway 를 통해 페이지에 람다의 리턴 값(sam test)을 표시하는 함수입니다.

import boto3
import json
import os
  
print('Loading function')
  
def  respond(err, res=None):
	return {
		'statusCode': '400'  if err else  '200',
		'body': err.message if err else json.dumps(res),
		'headers': {
			'Comtent-Type': 'application/json',
		},
	}
  
def  lambda_handler(event, context):
	print("Received event: " + json.dumps(event, indent=2))
	return respond(None, res="sam test")

template.yaml : 생성할 리소스의 템플릿
해당 템플릿에서는 람다 함수와 API Gateway가 생성됩니다.

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

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-gateway --capabilities CAPABILITY_IAM

3. 실행

이제 실제로 실행해보겠습니다.
실행 위의 commands.sh에 적힌 명령어를 순서대로 실행하겠습니다.

1) S3 버킷 생성

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

생성된 S3 버킷은 app.py 파일에서 정의한 람다 함수를 저장되는 목적으로 생성하고 나중에 CloudFormation 스택이 생성될 때 작성될 람다 함수의 코드를 가져오는데 사용합니다.

2) Cfn 패키지화 하기

aws cloudformation package --s3-bucket save-sam-code-202203 --template-file template.yaml --output-template-file gener/template-generated.yaml
# Uploading to 045da98e5cd11be5695060df3172ff1a  362 / 362.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>

결과적으로는 gener 폴터 안에 새로운 파일이 생성됩니다.
배포를 할 때는 생성된 template-generated.yaml 파일을 사용하게됩니다.

SAM
├─ gener
│  └─ template-generated.yaml
├─ scr
│  └─ app.py  
├─ commands.sh
└─ template.yaml

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/045da98e5cd11be5695060df3172ff1a
			Description: A Simple AWS Lambda function
			MemorySize: 128
			Timeout: 3
			Events:
				SamTestAPI:
					Type: Api
					Properties:
						Path: /sam
						Method: GET

3) 배포

이번에는 실제로 배포를 하겠습니다.
다음 명령어를 통해 CloudFormation에서 template-generated.yaml에 정의되어 있는 리소스를 생성하도록 합니다.

aws cloudformation deploy --template-file gener/template-generated.yaml --stack-name simple-lambda-gateway --capabilities CAPABILITY_IAM
# Waiting for changeset to be created..
# Waiting for stack create/update to complete
# Successfully created/updated stack - simple-lambda-gateway

4) 생성된 리소스의 확인

마지막으로 생성된 리소스를 확인하고 제대로 동작하는지 테스트해보겠습니다.

CloudFormation 스택

Lambda 람다도 잘 생성되어 있습니다. 같이 생성한 API Gateway가 트리거로 잘 설정이 되어 있는 것도 확인할 수 있습니다.

API Gateway 마지막으로 API Gateway도 잘 생성이 되었습니다.

그럼 이어서 생성된 리소스가 잘 생성되는지도 확인해보겠습니다.
먼저 생성한 API Gateway 리소스의 상세 페이지로 이동합니다.

그 중에서 [리소스] 탭으로 이동하면 GET이벤트를 테스트해볼 수 있습니다.
테스트를 눌러줍니다.

테스트 버튼을 눌러주면 오른쪽에 테스트 결과가 출력됩니다.
보이는 것처럼 람다의 리턴 값인 sam test가 잘 출력되었습니다.

이번에는 다른 방법으로도 확인해보겠습니다.
[스테이지]탭으로 이동해서 Prod를 선택합니다.
그러면 Prod 스테이지 편집기 가 오른쪽 페이지에 표시되는데 그중에서 맨 위에 있는 URL 호출에 있는 주소를 클릭합니다.

그러면 해당 URL 페이지로 들어가지는데 그 주소에template-generated.yaml에서 설정해준 Path인 /sam을 뒤에 붙여주면 다음과 같이 sam test가 출력됩니다.

이것으로 성공적으로 리소스가 잘 실행되는 걸 확인할 수 있었습니다.

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