백앤드(Back-End)/AWS

[AWS] Lambda 구축 (Serverless Framework)

RyanSin 2021. 9. 28. 15:52
반응형

- 개요

안녕하세요. 이번 시간에는 Serverless Framework를 사용해서 AWS Lambda 서비스를 구축하는 시간을 가져보도록 하겠습니다.

 

Serverless Framework란 AWS Lambda에서 Node.js를 사용해 애플리케이션 구축할 때 사용되는 프레임워크입니다.

 

Express, Koa를 사용해서 API 서버를 만드는데 이런 역할을 해준다고 생각하시면 됩니다.

 

- 설정

Serverless Framework를 사용하기 위해서는 패키지를 글로벌로 설치해야 합니다.

 

명령어
#npm
npm : npm install -g serverless

#yarn
yarn : yarn global add serverless

 

설치 확인
serverless create --tamplate
"aws-clojure-gradle", "aws-clojurescript-gradle", "aws-nodejs", "aws-nodejs-docker",
"aws-nodejs-typescript", "aws-alexa-typescript", "aws-nodejs-ecma-script", "aws-python"
"aws-python3", "aws-python-docker", "aws-groovy-gradle", "aws-java-maven", "aws-java-gradle",
"aws-kotlin-jvm-maven", "aws-kotlin-jvm-gradle", "aws-kotlin-jvm-gradle-kts"
"aws-kotlin-nodejs-gradle", "aws-scala-sbt", "aws-csharp", "aws-fsharp", "aws-go", "aws-go-dep",
"aws-go-mod", "aws-ruby"
"aws-provided"
"tencent-go", "tencent-nodejs", "tencent-python", "tencent-php"
"azure-csharp", "azure-nodejs", "azure-nodejs-typescript", "azure-python"
"cloudflare-workers", "cloudflare-workers-enterprise", "cloudflare-workers-rust"
"fn-nodejs", "fn-go"
"google-nodejs", "google-python", "google-go"
"kubeless-python", "kubeless-nodejs"
"knative-docker"
"openwhisk-java-maven", "openwhisk-nodejs", "openwhisk-php", "openwhisk-python", "openwhisk-ruby", "openwhisk-swift"
"spotinst-nodejs", "spotinst-python", "spotinst-ruby", "spotinst-java8"
"twilio-nodejs"
"aliyun-nodejs"
"plugin"
"hello-world".

정말 지원하는 템플릿이 많습니다. 여기서 우리는 aws-node.js를 사용하겠습니다.

 

프로젝트 생성
serverless create --template aws-nodejs --path serverless-api --name serverless-api

serverless create 명령어를 확인해보면

  • 템플릿 설정: --template aws-nodejs
  • 프로젝트 폴더 설정: --path hello-api
  • 프로젝트 이름 설정: --name hello-api
    프로젝트 생성

handler.js

'use strict';

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

  // Use this code if you don't use the http event with the LAMBDA-PROXY integration
  // return { message: 'Go Serverless v1.0! Your function executed successfully!', event };
};

AWS Console 환경에서 생성한 기본 소스코드가 설정되어 있습니다.

 

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: serverless-api
# 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: '2'

provider:
  name: aws
  runtime: nodejs12.x
  lambdaHashingVersion: 20201221

# 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:
#  include:
#    - include-me.js
#    - include-me-dir/**
#  exclude:
#    - exclude-me.js
#    - exclude-me-dir/**

functions:
  hello:
    handler: handler.hello
#    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"

serverless.yml 파일 프로젝트 환경설정을 담당하고 있습니다.

 

로컬 환경 테스트

명령어
serverless invoke local -f hello

명령어를 확인하면 serverless invoke 환경 이름 -f 함수명

 

정상적으로 동작하는 걸 확인할 수 있습니다. :)

 

AWS Lambda 배포

명령어
serverless deploy --stage production --region ap-northeast-2

명령어를 실행 시켜 성공했다면 위와 같은 화면이 나타납니다.

 

배포 확인

AWS에서 Lambda를 확인해보면 잘 배포된 걸 확인할 수 있습니다.

 

이번시간에는 Serverless Framework를 사용해서 AWS Lambda 서비스를 구축해보는 시간을 가졌습니다.

 

꼭 실습해보시는 걸 추천드리겠습니다. :)