はじめてのServerless(AWS)

Serverless(AWS)を使ってみました。

AWS Lambda上にクローラーを設置するのがゴールです。

インストール

Serverless Getting Started Guide

$ npm install -g serverless

# shell再読込
$ exec -l $SHELL

# グローバルにインストールしたくない場合には--save-devオプションを付ける
# ただし、パスを通すのが面倒かも
$ npm install --save-dev serverless

プロジェクト作成

Serverless Framework - AWS Lambda Guide - Quick Start

$ serverless create --template aws-nodejs --path my-service
$ cd my-service
$ ls
handler.js         serverless.yml

deploy

awscliのインストールおよびユーザー作成をしておく必要があります。 ユーザーにはadmin権限を追加しました。 必要最小限の権限については調査中です。

serverless.yml修正

regionを追加する。

$ cat serverless.yml
...
region: ap-northeast-1
...

handler.jsの修正は不要です。

deploy

作成したnodejsアプリ(handler.js)をdeployします。

$ serverless deploy
Serverless: Packaging service...
Serverless: Excluding development dependencies...
Serverless: Creating Stack...
Serverless: Checking Stack create progress...
.....
Serverless: Stack create finished...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Uploading service my-service.zip file to S3 (1.81 KB)...
Serverless: Validating template...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
................
Serverless: Stack update finished...
Service Information
service: my-service
stage: dev
region: ap-northeast-1
stack: my-service-dev
resources: 5
api keys:
  None
endpoints:
  None
functions:
  hello: my-service-dev-hello
layers:
  None

deploy時に以下のエラーが出た場合には、Admin権限を追加してみてください。(xxx,yyy,zzzは適当に読み替えてください)

  ServerlessError: User: arn:aws:iam::xxx:user/yyy is not authorized to perform: cloudformation:DescribeStacks on resource: arn:aws:cloudformation:ap-northeast-1:zzz:stack/my-service-dev/*

実行

$ serverless invoke -f hello
{
    "statusCode": 200,
    "body": "{\n  \"message\": \"Go Serverless v1.0! Your function executed successfully!\",\n  \"input\": {}\n}"
}

AWSコンソール

Lambda上にdeployされていることが確認できます。

f:id:unokun3:20190504110343p:plain
AWS Lambda

リンク