serverless frameworkでswaggerで定義したAPI GatewayとLambdaをデプロイする方法


はじめに

準備

AWS CLI、Node.js、serverless frameworkのインストールをしておきます。
AWS CLIは設定とかも完了していること。
それと、このプロジェクト用にディレクトリを作っておきます。ここで作業します。

console
$ pwd /Development
$ mkdir serverless
$ cd serverless

プロジェクトの作成

Lambda関数のpython3のテンプレートを使用
sls-testという名前で作成

console
$ sls create -t aws-python3 -p sls-test
Serverless: Generating boilerplate...
Serverless: Generating boilerplate in "/Development/serverless/sls-test"
 _______                             __
|   _   .-----.----.--.--.-----.----|  .-----.-----.-----.
|   |___|  -__|   _|  |  |  -__|   _|  |  -__|__ --|__ --|
|____   |_____|__|  \___/|_____|__| |__|_____|_____|_____|
|   |   |             The Serverless Application Framework
|       |                           serverless.com, v1.26.1
-------'

Serverless: Successfully generated boilerplate for template: "aws-python3"

$ cd sls-test

Lambda関数

とりあえず適当な文字を返すだけでいいので以下に書き換える

hello.py
def hello(event, context):
  message = 'serverless test'
  return message

swaggerファイル

/apiのみのシンプルな構成です。
リージョンは東京です。
<api name>や<account id>は適宜置き換える。
<lambda function name>はあとでserverlessの設定ファイルで一致させる必要があります。
変数的なもので置き換えられるなら誰か教えてください。

swagger.yaml
swagger: "2.0"
info:
  version: "1.0.0"
  title: "<api name>"
paths:
  /api:
    get:
      consumes:
      - "application/json"
      produces:
      - "application/json"
      responses:
        200:
          description: "200 response"
          schema:
            type: string
          headers:
            Access-Control-Allow-Origin:
              type: "string"
      x-amazon-apigateway-integration:
        responses:
          default:
            statusCode: "200"
        uri: "arn:aws:apigateway:ap-northeast-1:lambda:path/2015-03-31/functions/arn:aws:lambda:ap-northeast-1:<account id>:function:<lambda function name>/invocations"
        passthroughBehavior: "when_no_match"
        httpMethod: "POST"
        contentHandling: "CONVERT_TO_TEXT"
        type: "aws"

設定ファイルの編集

serverless.yml
最初はほとんどコメントアウトされていて

serverless.yml
service: sls-test
provider:
  name: aws
  runtime: python3.6
functions:
  hello:
    handler: handler.hello

これぐらいしか有効になっていないのでコメント外したり
追加したりしていきます。

serverless.yml
service: sls-test
provider:
  name: aws
  runtime: python3.6
  region: ap-northeast-1
functions:
  hello:
    name: <lambda function name>
    handler: handler.hello
resources:
  Resources:
    ApiGatewayRestApi:
      Type: AWS::ApiGateway::RestApi
      Properties:
        Body: ${file(../swagger.yaml)}
#        BodyS3Location:
#          Bucket: <bucket name>
#          Key: swagger.yaml

functionの名前は任意、他の設定などで使用しなければなんでもいい。
handlerは
<ファイル名(.pyを除く)>.<関数名>
です。

functions:
  hello:
    events:
      http:
        path: api
        method: get

こんな感じでAPI Gatewayを設定するとswaggerと衝突するので注意。
特にリソース名を同一にしたとき。

swagger仕様はインラインでも記述可
S3に保存しているswaggerを使用する場合は
BodyS3Locationで指定。

デプロイ

console
$ sls deploy

まとめ