⚡️ Serverless + Github Actions로 자동 배포! (1) - Serverless 앱 구성하기

정현문·2021년 6월 18일
3
post-thumbnail

개요

난 항상 개발을 하면서 자동화와 서버리스에 관해 관심이 굉장히 많았다.

최근에 프로젝트를 진행하던 중, 배포를 하는 단계에 도달하였다. 그래서 Serverless와 Github Actions를 사용해보기로 하였고, 내가 진행했던 방법을 토대로 과정을 공유해보고자 한다. 😀

이 시리즈는 총 2편으로 구성할 예정이다.
이번 1편에서는 예제 앱을 만들어 보고, Serverless로 배포 해 볼 것이다.

이 실습은 Mac OS 환경에서 진행하였습니다.😅 윈도우 환경은 살짝 상이할 수 있습니다.

⚡️ Serverless 앱 구성하기

✏️ 예제 앱 만들기

이번 실습에서 사용할 앱은 Typescript, Serverless 를 이용해서 간단하게 구성해 볼 것이다.

환경 구성하기

Serverless와 AWS CLI를 설치해준다.

yarn init
yarn global add serverless aws-cli

이번 앱에서 사용할 것들을 설치해준다. 그리고 aws에 접근하기 위해 다음 위치에 Credential을 설정해준다.

~/.aws/credentials

[default]
aws_access_key_id = <AWS에서 발급받은 ACCESS KEY ID>
aws_secret_access_key = <AWS에서 발급받은 SECRET ACCESS KEY>

앱 초기화

serverless에서 제공하는 템플릿을 사용해 볼 것이다. 다음 명령어를 사용하면 된다.

serverless create --template aws-nodejs

그러면 다음과 같은 구조가 될 것이다.

.
├── handler.js
├── package.json
└── serverless.yml

배포해보기 전에, serverless.yml에 있는 설정을 조금만 수정해보자. 😀

serverless.yml

service: serverless-github-actions # 배포하려는 서비스 이름
provider:
  name: aws
  runtime: nodejs12.x
  region: ap-northeast-2 # 배포하고자 하는 AWS 리전을 설정해 주었다.
functions:
  hello:
    handler: handler.hello # <파일 이름>.<함수 이름>
    events:     # http get 요청이 들어올 엔드포인트이다.
      - http:
          path: hello
          method: get

배포 테스트

그리고 바로 배포가 되는지 확인!

sls deploy
# sls는 serverless의 약칭이다.

성공적으로 배포가 완료되면 다음과 같은 결과가 나온다.

Serverless: Stack update finished...
Service Information
service: serverless-github-actions
stage: dev
region: ap-northeast-2
stack: serverless-github-actions-dev
resources: 11
api keys:
  None
endpoints:
  GET - https://~~~~~~~~~~.execute-api.ap-northeast-2.amazonaws.com/dev/hello
functions:
  hello: serverless-github-actions-dev-hello
layers:
  None

여기 보이는 엔드포인트로 접속하면 결과를 확인할 수 있다.

endpoints:
GET - https://~~~~~~~~~~.execute-api.ap-northeast-2.amazonaws.com/dev/hello

성공적으로 완료했으면 바로 다음 단계로 넘어가보자. 😀

💡 Typescript 적용하기

현재 템플릿으로 생성된 앱은 Javascript로 작성되어 있다. 이것을 Typescript로 바꾸고, 배포해보자.

Typescript 설치

Typescript를 사용하는데 필요한 패키지들을 설치해준다.

yarn add -D typescript serverless-plugin-typescript

이때 -D 옵션은 DevDependency로 설치하게 하는데,
이들은 개발시에만 사용되는 패키지이고, 실제 빌드 후 프로덕션 환경에서는 사용되지 않는 패키지이다.
Serverless는 이 DevDependency들은 제외하고 배포한다.

.ts 파일로 변환

handler.js 파일을 handler.ts로 확장자를 변경하고, 코드도 다음과 같이 살짝 수정해준다.

handler.ts

exports.hello = async (event) => {
  return {
    statusCode: 200,
    body: JSON.stringify(
      {
        message: 'Go Serverless v1.0! Your function executed successfully!',
        input: event,
      },
      null,
      2
    ),
  };
};

또한 tsconfig.json 파일을 다음과 같이 설정해준다.

tsconfig.json

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es2020",
        "lib": ["ES6"],
        "removeComments": true,
        "preserveConstEnums": true,
        "sourceMap": true
    }
}

Typescript plugin 적용

Serverless에 플러그인을 적용시키면, Typescript로 컴파일 후 빌드 된 파일을 배포하게 된다. serverless.yml 파일 하단에 다음을 추가한다.

serverless.yml

plugin: 
	- serverless-plugin-typescript

배포 해보기

sls deploy

다음과 같이 하면 Typescript 컴파일이 이루어진 후 배포되는 것을 확인할 수 있다 😀

마무리

이번 블로그에서는 Serverless로 앱을 배포해보는 단계까지 해 보았다.
다음 블로그에서는 이어서 Github Actions를 이용해서 자동으로 배포해 볼 것이다.

0개의 댓글