DevOps/AWS

Serverless 관리하기

mandarinko 2022. 12. 7. 20:09

Serverless 관리하기 라는 글을 쓰게 된 계기

현재 우리 회사에서는 수많은 Serverless를 사용하고 있다. 기존에는 cron을 위한 하나의 서버를 관리했었으나, cron기능중 하나가 죽어버리면 다른 기능들도 영향을 받는이유로 분산 관리를 했다. 하지만 분산관리에는 또 다른 문제점이 있었다.

AWS Lambda에 올려놓은 기능은 S3에 저장하게 되는데, 이때 어떠한 코드로 돌고 있는지 확인하는데 어려움이 있다.

따라서 Lambda에서 돌고있는 코드와 Codebuild에서 돌고있는 코드들을 하나의 repo에서 관리하면 좋겠다는 아이디어로 Serverless repo를 관리하게 되었다.

 

Lamdba를 사용하는 serverless 관리하기

리소스: Lambda는 github workflow와 servleless 프레임워크 조합을 사용한다 -> codebuild를 사용해서 배포하는것보다 조금 더 저렴하다고 한다.

 

동작원리:

  1. ./github/workflows 디렉토리 안에 있는 yml파일을 github에서 읽어서 action을 자동으로 추가
  2. yml파일로 github action이 추가되고 해당 action이 실행 이때 serverless 프레임워크를 이용해서 lambda로 배포
  3. serverless 프레임워크는 serverless.yml 파일을 읽고 lambda로 deploy함 serverless 상세설명
  4. 이때 어떤 디렉토리에 있는 serverless.yml 파일을 사용할지 /workflows 디렉토리 안에 있는 yml파일에서 지정해 주어야 함

관리방법:

 1. 루트 디렉토리에 workflow/xxx.yml추가

on:
	# push 될 때(바로 push, PR and merge 모두 push로 인식)
  push:
		# master브렌치로 push 될 때. 이때 개발 작업중이라면 생성한 브렌치로 설정
    branches:
      - master
		# 개발이 완료되고 위의 브렌치를 master로 바꾸어야 하는데 이때 paths를 설정해 주지 않으면 
		# master로 어떠한 코드가 병합될 때마다 모든 lambda가 다시 배포되는 불필요한 과정을 진행하기 때문에
		# master 브렌치로 push 되면서 아래 특정 path에 작업 될 때 지금의 yml파일로 생성된 action을
		# 동작할 수 있게 해줌
    paths:
      - teamwalk-rank-ttl/**

# github의 action에 들어갔을 때 action의 이름이 나타남
name: Teamwalk ranking ttl Auto Deploy to AWS Lambda

jobs:
  deploy:
    name: Auto Deploy
    runs-on: ubuntu-latest
		# 환경변수로 디렉토리 추가
    env:
      working-directory: ./teamwalk-rank-ttl

    steps:
      - uses: actions/checkout@main

      - name: Setup Node.js
        uses: actions/setup-node@v1
        with:
          node-version: '16.x'

      - name: Install Dependencies
        run: |
          npm install serverless -g
          npm install
				# 환경변수로 추가한 디렉토리 설정
        working-directory: ${{ env.working-directory }}

      - name: Deploy to Lambda
				# stage는 serverless.yml에 변수로 전달됨
        run: |
          sls deploy --stage test
          sls deploy --stage prod
        working-directory: ${{ env.working-directory }}

				# github에 등록해놓은 key
        env:
          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}

 2. 작업 디렉토리에 serverless.yml파일 추가

# Welcome to Serverless!
#
# This file is the main config file for your service.
# It's very minimal at this point and uses default values.
# You can always add more config options for more control.
# We've included some commented out config examples here.
# Just uncomment any of them to get that config option.
#
# For full config options, check the docs:
#    docs.serverless.com
#
# Happy Coding!

service: cashwalk-teamwalk-rank-ttl
# app and org for use with dashboard.serverless.com
#app: your-app-name
#org: your-org-name

# You can pin your service to only deploy with a specific Serverless version
# Check out our docs for more details
frameworkVersion: '3'

provider:
  name: aws
  runtime: nodejs16.x
  region: ap-northeast-1
  stage: ${opt:stage, 'test'}
  lambdaHashingVersion: 20201221
  iam:
    role: arn:aws:iam::119056747518:role/lambda_cashwalk

# you can overwrite defaults here
#  stage: dev
#  region: us-east-1

# you can add statements to the Lambda function's IAM Role here
#  iamRoleStatements:
#    - Effect: "Allow"
#      Action:
#        - "s3:ListBucket"
#      Resource: { "Fn::Join" : ["", ["arn:aws:s3:::", { "Ref" : "ServerlessDeploymentBucket" } ] ]  }
#    - Effect: "Allow"
#      Action:
#        - "s3:PutObject"
#      Resource:
#        Fn::Join:
#          - ""
#          - - "arn:aws:s3:::"
#            - "Ref" : "ServerlessDeploymentBucket"
#            - "/*"

# you can define service wide environment variables here
#  environment:
#    variable1: value1

# you can add packaging information here
#package:
#  patterns:
#    - '!exclude-me.js'
#    - '!exclude-me-dir/**'
#    - include-me.js
#    - include-me-dir/**

functions:
  setTTL:
    handler: handler.setTTL
    timeout: 300
#    events:
#      - schedule: cron(00 10-19/1 ? * * *)
#    events:
#      - schedule: cron(05 10,13 ? * * *)
#    The following are a few example events you can configure
#    NOTE: Please make sure to change your handler code to work with those events
#    Check the event documentation for details
#    events:
#      - httpApi:
#          path: /users/create
#          method: get
#      - websocket: $connect
#      - s3: ${env:BUCKET}
#      - schedule: rate(10 minutes)
#      - sns: greeter-topic
#      - stream: arn:aws:dynamodb:region:XXXXXX:table/foo/stream/1970-01-01T00:00:00.000
#      - alexaSkill: amzn1.ask.skill.xx-xx-xx-xx
#      - alexaSmartHome: amzn1.ask.skill.xx-xx-xx-xx
#      - iot:
#          sql: "SELECT * FROM 'some_topic'"
#      - cloudwatchEvent:
#          event:
#            source:
#              - "aws.ec2"
#            detail-type:
#              - "EC2 Instance State-change Notification"
#            detail:
#              state:
#                - pending
#      - cloudwatchLog: '/aws/lambda/hello'
#      - cognitoUserPool:
#          pool: MyUserPool
#          trigger: PreSignUp
#      - alb:
#          listenerArn: arn:aws:elasticloadbalancing:us-east-1:XXXXXX:listener/app/my-load-balancer/50dc6c495c0c9188/
#          priority: 1
#          conditions:
#            host: example.com
#            path: /hello

#    Define function environment variables here
#    environment:
#      variable2: value2

# you can add CloudFormation resource templates here
#resources:
#  Resources:
#    NewResource:
#      Type: AWS::S3::Bucket
#      Properties:
#        BucketName: my-new-bucket
#  Outputs:
#     NewOutput:
#       Description: "Description for the output"
#       Value: "Some output value"

3. serverless.yml 파일에서 설정해준 region에 lambda가 새로 배포된 것을 확인 할 수 있다.

 

 

Codebuild를 사용하는 serverless 관리하기

리소스: codebuild

동작원리:

  1. codebuild에서 특정 repo를 바라보도록 한다.
  2. 특정 codebuild가 사용할 buildspec.yml을 설정할 수 있고, buildspec.yml을 읽어서 codebuild를 실행

관리방법:

  1. Codebuild 생성
    1. aws의 codebuild 서비스로 이동해서 빌드 프로젝트 생성
    2. 소스탭의 소스 공급자를 GitHub으로 설정
    3. 내 GitHub 계정의 리포지토리를 선택하고 GitHub Oauth사용해서 연결Codebuild 생성

2. 코드 작성 및 buildspec.yml 파일 생성

version: 0.2

phases:
  install:
    runtime-versions:
      nodejs: 16
		# cd 명령어를 이용해서 작업 디렉토리 변경
    commands:
      - cd teamwalk-raffle
      - npm install

  build:
    commands:
      - node app.js
cache:
  paths:
    - 'node_modules/**/*'