AWS SAM - Severless Application Model

Human Being·2022년 3월 27일
0

AWS

목록 보기
5/6
post-thumbnail

Serverless Application

이벤트가 들어올 때만 켜지는 식으로 동작하여 Serverless로 불린다
EC2에 모든 기능을 구현했다면 이벤트가 없을 때도 켜두어야 하기에 비용이 많이 청구된다
그리고 트래픽이 몰릴 때 인스턴스를 더 좋은 걸로 올려야 하는 등 고려할게 많다

이러한 이유로 무조건 Serverless가 좋다는 것은 아니다
이벤트가 올 때만 켜지기에 첫 시작에 Cold time이 필요하다
이를 방지하기 위해 지속적으로 이벤트를 보내는 코드도 만들거나
Cold time을 감안하여 코드를 작성할 수 있다면 괜찮은 조건이 아닐까 싶다

SAM

Serverless application을 빌드 및 배포하는 데 사용한다
Docker build에 대한 이해가 필요하다

아래 글에는 AWS SAM CLI 설치하는 방법에 대해서 나와있다
운영체제에 맞게 진행하면 된다
설치 제거 방법 또한 나와있다
https://docs.aws.amazon.com/ko_kr/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html

AWS Lambda 배포

출처 : https://docs.aws.amazon.com/ko_kr/serverless-application-model/latest/developerguide/serverless-getting-started-hello-world.html

AWS Lambda와 API Gateway를 미리 연결시켜주고 그 환경도 마련해주는 Hello World 애플리케이션을 배포해보자

아래 사이트를 참고해서 진행해보면 된다

https://docs.aws.amazon.com/ko_kr/serverless-application-model/latest/developerguide/serverless-getting-started-hello-world.html

#Step 1 - Download a sample application
sam init

#Step 2 - Build your application
cd sam-app
sam build

#Step 3 - Deploy your application
sam deploy --guided

추가 설명

디렉토리 구조는 다음과 같다

 sam-app/
   ├── README.md
   ├── events/        # 여기에 event 변수에 보낼 jSON 내용을 저장
   │   └── event.json
   ├── hello_world/   # 실제로 build 되는 폴더
   │   ├── __init__.py
   │   ├── app.py            #Lambda handler 코드를 작성하는 곳
   │   └── requirements.txt  #Python 패키지 내용 저장
   ├── template.yaml         #AWS SAM template 정의
   └── tests/
       └── unit/
           ├── __init__.py
           └── test_handler.py
        

sam build 시 참고하는 파일 중 하나로 template.yaml (template.yml)이 있다
예로 람다라면 여기에 람다의 최대 메모리와 가동 시간 등의 옵션을 설정할 수 있다

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  python3.9

  Sample SAM Template for lambda-python3.9

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 900 ### 최대 가동 시간

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      MemorySize: 3008  ## 최대 메모리
      PackageType: Image

만약에 image 형태로 생성했다면 hello_world 안에 Dockerfile이 생성된다

Lambda Dockerfile은
언어 자체로 FROM을 해서 디버깅하기 까다로울 수 있지만
실상 뜯어보면 Amazon Linux 2 일 뿐이다

해당 파일로 docker build를 하고 docker run을 하면 파이썬 실행 모습만 나오지만
이를 docker exec으로 접속하면 linux 화면이 나오니
거기서 수정하면 편하다

또 몇몇 파이썬 모듈은 리눅스 자체에 무언가를 설치해야될 때가 있어
그럴 때는 Dockerfile에 yum install 키워드를 적어두면 된다

FROM public.ecr.aws/lambda/python:3.9

RUN yum update -y && yum install -y git

COPY requirements.txt ./
RUN python3.9 -m pip install -r requirements.txt 

COPY app.py ./
CMD ["app.lambda_handler"]

머신러닝 용도로 쉽게 생성하기

0개의 댓글