88
JAWSで作る サーバレスAPIアプリケーション AWS モバイル/IoTサービス徹底攻略!! - Developers.IO Meetup番外編 - 1 2015-11-21 クラスメソッド株式会社 五十嵐良輔

AWSで作る サーバレスAPIアプリケーション

Embed Size (px)

Citation preview

Page 1: AWSで作る サーバレスAPIアプリケーション

JAWSで作るサーバレスAPIアプリケーション

AWS モバイル/IoTサービス徹底攻略!!

- Developers.IO Meetup番外編 -

1

2015-11-21 クラスメソッド株式会社 五十嵐良輔

Page 2: AWSで作る サーバレスAPIアプリケーション

自己紹介• 五十嵐 良輔• クラスメソッド株式会社• モバイルアプリサービス部• 現在の仕事はRailsとAWSが中心

• ブログではRailsとJAWSネタを書いていますhttp://dev.classmethod.jp/author/igarashi-ryosuke/

2

Page 3: AWSで作る サーバレスAPIアプリケーション

アジェンダ• JAWSの紹介 *

• AWSMの紹介 *

• サンプルプロジェクトの解説• まとめ* 10/30に弊社で行われた「モバイルバックエンド勉強会 In 秋葉原 」で発表したものとほぼ同じ内容です。http://dev.classmethod.jp/server-side/framework/jaws-awsm-users/

3

Page 4: AWSで作る サーバレスAPIアプリケーション

JAWSの紹介Just AWS Without Servers

4

Page 5: AWSで作る サーバレスAPIアプリケーション

現状の問題• LambdaやAPI Gatewayを使って開発をしようとすると・・・

5

Page 6: AWSで作る サーバレスAPIアプリケーション

現状の問題• LambdaやAPI Gatewayを使って開発をしようとすると・・・

6

Lambdaにnpmを使いたいんだけど・・・

Page 7: AWSで作る サーバレスAPIアプリケーション

現状の問題• LambdaやAPI Gatewayを使って開発をしようとすると・・・

7

Lambdaにnpmを使いたいんだけど・・・ Lambdaのデプロイは関

連するファイルをzipしてs3にアップして・・・

Page 8: AWSで作る サーバレスAPIアプリケーション

現状の問題• LambdaやAPI Gatewayを使って開発をしようとすると・・・

8

Lambdaにnpmを使いたいんだけど・・・ Lambdaのデプロイは関

連するファイルをzipしてs3にアップして・・・

LambdaのCFn書いて・・・

Page 9: AWSで作る サーバレスAPIアプリケーション

現状の問題• LambdaやAPI Gatewayを使って開発をしようとすると・・・

9

Lambdaにnpmを使いたいんだけど・・・ Lambdaのデプロイは関

連するファイルをzipしてs3にアップして・・・

LambdaのCFn書いて・・・ API GatewayはCFnま

だ対応してない・・・

Page 10: AWSで作る サーバレスAPIアプリケーション

現状の問題• LambdaやAPI Gatewayを使って開発をしようとすると・・・

10

Lambdaにnpmを使いたいんだけど・・・ Lambdaのデプロイは関

連するファイルをzipしてs3にアップして・・・

LambdaのCFn書いて・・・ API GatewayはCFnま

だ対応してない・・・必要なIAMを作ってなかった・・・

Page 11: AWSで作る サーバレスAPIアプリケーション

現状の問題• LambdaやAPI Gatewayを使って開発をしようとすると・・・

11

Lambdaにnpmを使いたいんだけど・・・ Lambdaのデプロイは関

連するファイルをzipしてs3にアップして・・・

LambdaのCFn書いて・・・ API GatewayはCFnま

だ対応してない・・・必要なIAMを作ってなかった・・・ ローカルでテストした

い・・

Page 12: AWSで作る サーバレスAPIアプリケーション

現状の問題• LambdaやAPI Gatewayを使って開発をしようとすると・・・

12

Lambdaにnpmを使いたいんだけど・・・ Lambdaのデプロイは関

連するファイルをzipしてs3にアップして・・・

LambdaのCFn書いて・・・ API GatewayはCFnま

だ対応してない・・・必要なIAMを作ってなかった・・・ ローカルでテストした

い・・

Lambdaに機微な情報を書きたくない・・

Page 13: AWSで作る サーバレスAPIアプリケーション

現状の問題• LambdaやAPI Gatewayを使って開発をしようとすると・・・

13

Lambdaにnpmを使いたいんだけど・・・ Lambdaのデプロイは関

連するファイルをzipしてs3にアップして・・・

LambdaのCFn書いて・・・ API GatewayはCFnま

だ対応してない・・・必要なIAMを作ってなかった・・・ ローカルでテストした

い・・

Lambdaに機微な情報を書きたくない・・

いろいろと大変!!

Page 14: AWSで作る サーバレスAPIアプリケーション

14

https://github.com/jaws-framework/JAWS

Page 15: AWSで作る サーバレスAPIアプリケーション

15

https://github.com/jaws-framework/JAWS

JAWSが解決します!!

Page 16: AWSで作る サーバレスAPIアプリケーション

JAWSとは• AWS LambdaとAPI GatewayをベースにAWS上でサーバレスなアプリケーションを作るフレームワーク

• 実態はCLIツール(今のところ)

• Lambdaの雛形を作ったり、必要なリソースのCloudFormationテンプレートなどを自動生成・デプロイしてくれる

• オープンソース• v1.3 ベータ(2015-11-21時点)

16

Page 17: AWSで作る サーバレスAPIアプリケーション

アーキテクチャ(最小構成)

17

API Gateway Lambda

http://dev.classmethod.jp/cloud/aws/getting-started-with-api-gateway-lambda-integration/

JAWSがカバーする範囲

Page 18: AWSで作る サーバレスAPIアプリケーション

プロジェクト構成• aws_modules機能の単位であり、複数のLambdaとリソースを構成するためのCFnの定義からなる

• cloudformation プロジェクトに必要なリソース全てを構成するためのCFnの定義

• その他環境変数やプロジェクトの構成ファイル

18

Page 19: AWSで作る サーバレスAPIアプリケーション

プロジェクト構成• aws_modules機能の単位であり、複数のLambdaとリソースを構成するためのCFnの定義からなる

• cloudformation プロジェクトに必要なリソース全てを構成するためのCFnの定義

• その他環境変数やプロジェクトの構成ファイル

19

Page 20: AWSで作る サーバレスAPIアプリケーション

プロジェクト構成• aws_modules機能の単位であり、複数のLambdaとリソースを構成するためのCFnの定義からなる

• cloudformation プロジェクトに必要なリソース全てを構成するためのCFnの定義

• その他環境変数やプロジェクトの構成ファイル

20

Page 21: AWSで作る サーバレスAPIアプリケーション

デプロイ構成• 複数ステージ• 複数リージョン• 3つのCloudFormationスタック• Resources• Lambdas• API Gateway

21

Page 22: AWSで作る サーバレスAPIアプリケーション

デプロイ構成• 複数ステージ• 複数リージョン• 3つのCloudFormationスタック• Resources• Lambdas• API Gateway

22

Page 23: AWSで作る サーバレスAPIアプリケーション

デプロイ構成• 複数ステージ• 複数リージョン• 3つのCloudFormationスタック• Resources• Lambdas• API Gateway

23

Page 24: AWSで作る サーバレスAPIアプリケーション

AWSMの紹介AWS Module

24

Page 25: AWSで作る サーバレスAPIアプリケーション

AWS Module(AWSM)とは• JAWSプロジェクトにおける機能の単位• リソースもまとめて管理• LambdaとAPI Gateway

• S3やDynamoDBなどその他のAWSサービス

• npmと同じ構成• 再利用可能• 現在はNode.jsのみ(他の言語にも対応予定)

25

Page 26: AWSで作る サーバレスAPIアプリケーション

AWSM一覧• awsm-images画像を編集(リサイズなど)するREST APIを生成する

• awsm-usersDynamoDBを使ってユーザを作成・認証する

• awsm-cloudfrontS3の前にCloudFrontを配置して、API Gatewayでエンドポイ

ントを作成する

26

Page 27: AWSで作る サーバレスAPIアプリケーション

AWSM一覧• awsm-middleware• awsm-loggly• awsm-twilio• awsm-stripe-webhook• awsm-slack-webhook• awsm-mailer• awsm-s3tokenvendor• joumae-users / joumae-resources• など

27

Page 28: AWSで作る サーバレスAPIアプリケーション

サンプルプログラムの解説

28

Page 29: AWSで作る サーバレスAPIアプリケーション

作ったもの• GithubへのコメントをSlackに通知する

Webhook API• やりたかったこと• PRへのCommentだけをSlackに通知

• Githubのユーザ名をSlackのユーザ名に変換

29

Page 30: AWSで作る サーバレスAPIアプリケーション

作ったもの• GithubへのコメントをSlackに通知する

Webhook API• やりたかったこと• PRへのCommentだけをSlackに通知

• GithubのAPIはIssueとPRの区別がない

• Githubのユーザ名をSlackのユーザ名に変換

30

Page 31: AWSで作る サーバレスAPIアプリケーション

作ったもの• イメージ図

31

Webhook

Page 32: AWSで作る サーバレスAPIアプリケーション

作ったもの• イメージ図

32

Webhook

API Gateway

HTTPリクエストJSON JSON

Lambda

JSONをごにょごにょ

Page 33: AWSで作る サーバレスAPIアプリケーション

プロジェクトの作成

33

Page 34: AWSで作る サーバレスAPIアプリケーション

プロジェクトの作成$ jaws project create ____ _____ __ __ _________ | | / _ \/ \ / \/ _____/ | |/ /_\ \ \/\/ /\_____ \ /\__| / | \ / / \ \________\____|__ /\__/\__/ /_________/ v1 (BETA) *** The Server-Less Framework *** JAWS: Enter a project name: (jaws-E1XgDRPWx) demo JAWS: Enter a project domain (You can change this at any time: (myapp.com) JAWS: Enter an email to use for AWS alarms: ([email protected]) JAWS: Enter a stage for this project: (dev) JAWS: Select a region for your project: us-east-1 us-west-2 eu-west-1 > ap-northeast-1 JAWS: Select an AWS profile for your project: > default JAWS: Creating CloudFormation Stack for your new project (~5 mins)...

34

project createコマンドでプロジェクトを作成開始

Page 35: AWSで作る サーバレスAPIアプリケーション

プロジェクトの作成$ jaws project create ____ _____ __ __ _________ | | / _ \/ \ / \/ _____/ | |/ /_\ \ \/\/ /\_____ \ /\__| / | \ / / \ \________\____|__ /\__/\__/ /_________/ v1 (BETA) *** The Server-Less Framework *** JAWS: Enter a project name: (jaws-E1XgDRPWx) demo JAWS: Enter a project domain (You can change this at any time: (myapp.com) JAWS: Enter an email to use for AWS alarms: ([email protected]) JAWS: Enter a stage for this project: (dev) JAWS: Select a region for your project: us-east-1 us-west-2 eu-west-1 > ap-northeast-1 JAWS: Select an AWS profile for your project: > default JAWS: Creating CloudFormation Stack for your new project (~5 mins)...

35

プロジェクト名

Page 36: AWSで作る サーバレスAPIアプリケーション

プロジェクトの作成$ jaws project create ____ _____ __ __ _________ | | / _ \/ \ / \/ _____/ | |/ /_\ \ \/\/ /\_____ \ /\__| / | \ / / \ \________\____|__ /\__/\__/ /_________/ v1 (BETA) *** The Server-Less Framework *** JAWS: Enter a project name: (jaws-E1XgDRPWx) demo JAWS: Enter a project domain (You can change this at any time: (myapp.com) JAWS: Enter an email to use for AWS alarms: ([email protected]) JAWS: Enter a stage for this project: (dev) JAWS: Select a region for your project: us-east-1 us-west-2 eu-west-1 > ap-northeast-1 JAWS: Select an AWS profile for your project: > default JAWS: Creating CloudFormation Stack for your new project (~5 mins)...

36

プロジェクトドメイン

Page 37: AWSで作る サーバレスAPIアプリケーション

プロジェクトの作成$ jaws project create ____ _____ __ __ _________ | | / _ \/ \ / \/ _____/ | |/ /_\ \ \/\/ /\_____ \ /\__| / | \ / / \ \________\____|__ /\__/\__/ /_________/ v1 (BETA) *** The Server-Less Framework *** JAWS: Enter a project name: (jaws-E1XgDRPWx) demo JAWS: Enter a project domain (You can change this at any time: (myapp.com) JAWS: Enter an email to use for AWS alarms: ([email protected]) JAWS: Enter a stage for this project: (dev) JAWS: Select a region for your project: us-east-1 us-west-2 eu-west-1 > ap-northeast-1 JAWS: Select an AWS profile for your project: > default JAWS: Creating CloudFormation Stack for your new project (~5 mins)...

37

通知用メールアドレス

Page 38: AWSで作る サーバレスAPIアプリケーション

プロジェクトの作成$ jaws project create ____ _____ __ __ _________ | | / _ \/ \ / \/ _____/ | |/ /_\ \ \/\/ /\_____ \ /\__| / | \ / / \ \________\____|__ /\__/\__/ /_________/ v1 (BETA) *** The Server-Less Framework *** JAWS: Enter a project name: (jaws-E1XgDRPWx) demo JAWS: Enter a project domain (You can change this at any time: (myapp.com) JAWS: Enter an email to use for AWS alarms: ([email protected]) JAWS: Enter a stage for this project: (dev) JAWS: Select a region for your project: us-east-1 us-west-2 eu-west-1 > ap-northeast-1 JAWS: Select an AWS profile for your project: > default JAWS: Creating CloudFormation Stack for your new project (~5 mins)...

38

デフォルトの環境名

Page 39: AWSで作る サーバレスAPIアプリケーション

プロジェクトの作成$ jaws project create ____ _____ __ __ _________ | | / _ \/ \ / \/ _____/ | |/ /_\ \ \/\/ /\_____ \ /\__| / | \ / / \ \________\____|__ /\__/\__/ /_________/ v1 (BETA) *** The Server-Less Framework *** JAWS: Enter a project name: (jaws-E1XgDRPWx) demo JAWS: Enter a project domain (You can change this at any time: (myapp.com) JAWS: Enter an email to use for AWS alarms: ([email protected]) JAWS: Enter a stage for this project: (dev) JAWS: Select a region for your project: us-east-1 us-west-2 eu-west-1 > ap-northeast-1 JAWS: Select an AWS profile for your project: > default JAWS: Creating CloudFormation Stack for your new project (~5 mins)...

39

デフォルトのリージョン

Page 40: AWSで作る サーバレスAPIアプリケーション

プロジェクトの作成$ jaws project create ____ _____ __ __ _________ | | / _ \/ \ / \/ _____/ | |/ /_\ \ \/\/ /\_____ \ /\__| / | \ / / \ \________\____|__ /\__/\__/ /_________/ v1 (BETA) *** The Server-Less Framework *** JAWS: Enter a project name: (jaws-E1XgDRPWx) demo JAWS: Enter a project domain (You can change this at any time: (myapp.com) JAWS: Enter an email to use for AWS alarms: ([email protected]) JAWS: Enter a stage for this project: (dev) JAWS: Select a region for your project: us-east-1 us-west-2 eu-west-1 > ap-northeast-1 JAWS: Select an AWS profile for your project: > default JAWS: Creating CloudFormation Stack for your new project (~5 mins)...

40

使用するプロファイル

Page 41: AWSで作る サーバレスAPIアプリケーション

プロジェクトの作成$ jaws project create ____ _____ __ __ _________ | | / _ \/ \ / \/ _____/ | |/ /_\ \ \/\/ /\_____ \ /\__| / | \ / / \ \________\____|__ /\__/\__/ /_________/ v1 (BETA) *** The Server-Less Framework *** JAWS: Enter a project name: (jaws-E1XgDRPWx) demo JAWS: Enter a project domain (You can change this at any time: (myapp.com) JAWS: Enter an email to use for AWS alarms: ([email protected]) JAWS: Enter a stage for this project: (dev) JAWS: Select a region for your project: us-east-1 us-west-2 eu-west-1 > ap-northeast-1 JAWS: Select an AWS profile for your project: > default JAWS: Creating CloudFormation Stack for your new project (~5 mins)...

41

何分かすると最低限必要のリソース(LambdaとAPI GatewayのIAM)が作成されます。

Page 42: AWSで作る サーバレスAPIアプリケーション

プロジェクトとAWSMの雛形を作成

42

Page 43: AWSで作る サーバレスAPIアプリケーション

プロジェクトの雛形.├── README.md

├── admin.env

├── aws_modules

├── cloudformation

├── jaws.json

├── lib

├── node_modules

├── package.json

└── tests

43

Page 44: AWSで作る サーバレスAPIアプリケーション

プロジェクトの雛形.├── README.md

├── admin.env

├── aws_modules

├── cloudformation

├── jaws.json

├── lib

├── node_modules

├── package.json

└── tests

44

使用するプロファイルの設定など

Page 45: AWSで作る サーバレスAPIアプリケーション

プロジェクトの雛形.├── README.md

├── admin.env

├── aws_modules

├── cloudformation

├── jaws.json

├── lib

├── node_modules

├── package.json

└── tests

45

AWSMのディレクトリ

Page 46: AWSで作る サーバレスAPIアプリケーション

プロジェクトの雛形.├── README.md

├── admin.env

├── aws_modules

├── cloudformation

├── jaws.json

├── lib

├── node_modules

├── package.json

└── tests

46

CloudFormationテンプレートのディレクトリ

Page 47: AWSで作る サーバレスAPIアプリケーション

プロジェクトの雛形.├── README.md

├── admin.env

├── aws_modules

├── cloudformation

├── jaws.json

├── lib

├── node_modules

├── package.json

└── tests

47

プロジェクトの環境設定

Page 48: AWSで作る サーバレスAPIアプリケーション

プロジェクトの雛形.├── README.md

├── admin.env

├── aws_modules

├── cloudformation

├── jaws.json

├── lib

├── node_modules

├── package.json

└── tests

48

プロジェクトが使用するソースコードのディレクトリ

Page 49: AWSで作る サーバレスAPIアプリケーション

プロジェクトの雛形.├── README.md

├── admin.env

├── aws_modules

├── cloudformation

├── jaws.json

├── lib

├── node_modules

├── package.json

└── tests

49

プロジェクトが使用するnpmのディレクトリ

Page 50: AWSで作る サーバレスAPIアプリケーション

プロジェクトの雛形.├── README.md

├── admin.env

├── aws_modules

├── cloudformation

├── jaws.json

├── lib

├── node_modules

├── package.json

└── tests

50

プロジェクトの基本設定や依存関係のあるnpmを定義

Page 51: AWSで作る サーバレスAPIアプリケーション

プロジェクトの雛形.├── README.md

├── admin.env

├── aws_modules

├── cloudformation

├── jaws.json

├── lib

├── node_modules

├── package.json

└── tests

51

テストディレクトリ

Page 52: AWSで作る サーバレスAPIアプリケーション

AWSMの作成$ jaws module create awsm-github-webhook slack

52

モジュール名 機能名

Page 53: AWSで作る サーバレスAPIアプリケーション

AWSMの作成$ jaws module create awsm-github-webhook slackaws_modules└── awsm-github-webhook ├── awsm.json └── slack ├── awsm.json ├── event.json ├── handler.js └── index.js

53

これらが雛形として作られる

Page 54: AWSで作る サーバレスAPIアプリケーション

API Gatewayと対比すると$ jaws module create awsm-github-webhook slack

aws_modules└── awsm-github-webhook ├── awsm.json └── slack ├── awsm.json ├── event.json ├── handler.js └── index.js

54

この先にLambda Function

Resource

Action

Page 55: AWSで作る サーバレスAPIアプリケーション

AWSMの構成aws_modules└── awsm-github-webhook ├── awsm.json └── slack ├── awsm.json ├── event.json ├── handler.js └── index.js

55

AWSMの環境設定や、AWSM全体に必要なリソース

Page 56: AWSで作る サーバレスAPIアプリケーション

awsm.json(全体){ "name": "github-webhook", "version": "0.0.1", "location": "https://github.com/...", "author": "", "description": "", "resources": { "cloudFormation": { "LambdaIamPolicyDocumentStatements": [], "ApiGatewayIamPolicyDocumentStatements": [], "Resources": {} } } }

56

LambdaのIAMロールポリシー

API GatewayのIAMロールポリシーその他必要なリソース

Page 57: AWSで作る サーバレスAPIアプリケーション

AWSMの構成aws_modules└── awsm-github-webhook ├── awsm.json └── slack ├── awsm.json ├── event.json ├── handler.js └── index.js

57

個別のアクションに必要な設定

Page 58: AWSで作る サーバレスAPIアプリケーション

awsm.json(個別){ "lambda": { "envVars": [], "deploy": true, "package": { "optimize": { "builder": "browserify", "minify": true, "ignore": [], "exclude": [ "aws-sdk" ], "includePaths": [] }, "excludePatterns": [] }, "cloudFormation": { "Description": "", "Handler": "aws_modules/github-webhook/slack/handler.handler", "MemorySize": 1024, "Runtime": "nodejs", "Timeout": 6 } },

58

環境変数

パッケージ設定

Lambdaの設定

Page 59: AWSで作る サーバレスAPIアプリケーション

awsm.json(個別) "apiGateway": { "deploy": true, "cloudFormation": { "Type": "AWS", "Path": "github-webhook/slack", "Method": "GET", "AuthorizationType": "none", "ApiKeyRequired": false, "RequestTemplates": {}, "RequestParameters": {}, "Responses": { "400": { "statusCode": "400" }, "default": { "statusCode": "200", "responseParameters": {}, "responseModels": {}, "responseTemplates": { "application/json": "" } } } } } }

59

API Gatewayの設定

Page 60: AWSで作る サーバレスAPIアプリケーション

AWSMの構成aws_modules└── awsm-github-webhook ├── awsm.json └── slack ├── awsm.json ├── event.json ├── handler.js └── index.js

60

ローカルでテストするときのテストデータ

Page 61: AWSで作る サーバレスAPIアプリケーション

event.json{}

61

Page 62: AWSで作る サーバレスAPIアプリケーション

AWSMの構成aws_modules└── awsm-github-webhook ├── awsm.json └── slack ├── awsm.json ├── event.json ├── handler.js └── index.js

62

Lambda のエントリーポイント

Page 63: AWSで作る サーバレスAPIアプリケーション

handler.js'use strict';

/** * AWS Module: Action: Lambda Handler * "Your lambda functions should be a thin wrapper around your own separate * modules, to keep your code testable, reusable and AWS independent" */

require('jaws-core-js/env');

// Modularized Code var action = require('./index.js');

// Lambda Handler module.exports.handler = function(event, context) { action.run(event, context, function(error, result) { return context.done(error, result); }); };

63

環境変数を読み込んだりする

実際の処理を記述する

Lambdaのエントリーポイント

Page 64: AWSで作る サーバレスAPIアプリケーション

AWSMの構成aws_modules└── awsm-github-webhook ├── awsm.json └── slack ├── awsm.json ├── event.json ├── handler.js └── index.js

64

実際の処理部分

Page 65: AWSで作る サーバレスAPIアプリケーション

index.js/** * AWS Module: Action: Modularized Code */

// Export For Lambda Handler module.exports.run = function(event, context, cb) { return cb(null, action()); };

// Your Code var action = function() { return {message: 'Your JAWS lambda executed successfully!'}; };

65

handler.jsから呼ばれる部分

実際の処理実装を書く部分

Page 66: AWSで作る サーバレスAPIアプリケーション

ここから編集

66

Page 67: AWSで作る サーバレスAPIアプリケーション

HTTP Methodを変更する# aws_modules/awsm-github-webhook/slack/awsm.json

"apiGateway": { "cloudFormation": { "Type": "AWS", "Path": "awsm-github-webhook/slack", + "Method": "POST", "AuthorizationType": "none", "ApiKeyRequired": false, "RequestTemplates": {},

67

MethodをPOSTに変更

Page 68: AWSで作る サーバレスAPIアプリケーション

npmを追加する$ npm install request --save

68

# package.json

"dependencies": { "jaws-core-js": "~0.0.2" + "request": "^2.65.0" }

requestを追加

Page 69: AWSで作る サーバレスAPIアプリケーション

SlackのWebhookへPOSTする# aws_modules/awsm-github-webhook/slack/index.js

+var request = require('request');

module.exports.run = function(event, context, cb) { + // Slackのincoming-webhook URL + // TODO: Varsから取得する + var webhookUrl = 'https://hooks.slack.com/services/XXXXXXXX'; + + // SlackへPOSTするパラメータを作成 + var text = event.comment.body + '<' + event.comment.html_url + '>'; + text = text.replace("@cm-igarashi-ryosuke", "@cm-igarashi"); + var params = { text: text }; + + // Slackのincoming-webhook URLにパラメータをつけてPOSTする + request.post(webhookUrl, { form: { payload: JSON.stringify(params) } }, + function (err, res, body) { + return cb(null, {message: body}); + } + ); };

69

Page 70: AWSで作る サーバレスAPIアプリケーション

テスト# aws_modules/awsm-github-webhook/slack/event.json

{ "comment": { "html_url": "https://github.com/xxx/xxx/issues/124#issuecomment-156993922", "body": "@cm-igarashi-ryosuke てすと" } }

70

$ cd aws_modules/awsm-github-webhook/slack

$ jaws run

JAWS: {"message":"ok"}

テストデータを追加

Page 71: AWSで作る サーバレスAPIアプリケーション

$ jaws env set dev ap-northeast-1 WEBHOOK_URL \

https://hooks.slack.com/services/XXXXXXXX

環境変数の設定# aws_modules/awsm-github-webhook/slack/awsm.json

{ "lambda": { - "envVars": [], + "envVars": [ + "WEBHOOK_URL" + ],

71

環境変数名環境変数の値

Page 72: AWSで作る サーバレスAPIアプリケーション

環境変数の参照# aws_modules/awsm-github-webhook/slack/index.js

module.exports.run = function(event, context, cb) { // Slackのincoming-webhook URL - // TODO: Varsから取得する - var webhookUrl = 'https://hooks.slack.com/services/XXXXXXXX'; + var webhookUrl = process.env.WEBHOOK_URL;

72

環境変数から値を取得するよう修正

Page 73: AWSで作る サーバレスAPIアプリケーション

ヘッダー情報を参照する# aws_modules/awsm-github-webhook/slack/awsm.json

"ApiKeyRequired": false, - "RequestTemplates": {}, + "RequestTemplates": { + "application/json": "{\"x_github_event\": \"$input.params('X-GitHub-Event')\", \"body\": $input.json('$')}" + }, "RequestParameters": {},

73

リクエストHeaderの’X-GitHub-Event’の値を、Lambdaのパラメータ(event.x_github_event)に渡す

リクエストbodyをevent.bodyに渡す

Page 74: AWSで作る サーバレスAPIアプリケーション

ヘッダー情報を参照する# aws_modules/awsm-github-webhook/slack/index.js

module.exports.run = function(event, context, cb) {

+ // X-GitHub-Eventの値が「issue_comment」でない場合は処理を終了 + if(event.x_github_event != 'issue_comment') { + return cb(null, action()); + }

- var text = event.comment.body + '<' + event.comment.html_url + '>'; + var text = event.body.comment.body + '<' + event.body.comment.html_url + '>';

74

Page 75: AWSで作る サーバレスAPIアプリケーション

デプロイ$ jaws dash

JAWS: Dashboard for project "demo"

-------------------------------------------

Project Summary

-------------------------------------------

Stages:

dev ap-northeast-1

Lambdas: 1

Endpoints: 1

-------------------------------------------

Select Resources To Deploy

-------------------------------------------

awsm/slack

L) lAwsmGithubWebhookSlack

E) /awsm-github-webhook/slack - POST

- - - - -

> Deploy Selected -->

75

デプロイするリソースを選択

jaws dashコマンド

Page 76: AWSで作る サーバレスAPIアプリケーション

実行例

76

GithunのIssueにコメントすると・・・

Page 77: AWSで作る サーバレスAPIアプリケーション

実行例

77

GithunのIssueにコメントすると・・・

Slackに通知される!(メンションの名前が変わっています)

Page 78: AWSで作る サーバレスAPIアプリケーション

NPMとして公開する

78

Page 79: AWSで作る サーバレスAPIアプリケーション

AWSMをNPMにするときの構造awsm-github-webhook

awsm.json

package.json

awsm

slack

awsm.json

handler.js

index.js

event.json

lib

modularcode.js

79

npmの設定

Lambdaの部分はawsmディレクトリに入れるここにあるコードはカスタマイズして使われる想定

libディレクトリにはカスタマイズして欲しくないコードを入れる

Page 80: AWSで作る サーバレスAPIアプリケーション

NPM初期化$ cd aws_modules/awsm-github-webhook$ npm initname: (awsm-github-webhook)version: (1.0.0)description:entry point: (index.js)test command:git repository:keywords:author:license: (ISC)About to write to /Users/igarashi.ryosuke/temp/jaws/test/aws_modules/awsm-github-webhook/package.json:

$ mkdir awsm && mv slack awsm/slack80

対話的にnpmの初期設定

awsmディレクトリに移動

package.jsonが作られる

Page 81: AWSで作る サーバレスAPIアプリケーション

package.jsonの設定# aws_modules/awsm-github-webhook/package.json

"scripts": { + "postinstall": "jaws postinstall awsm-github-webhook npm" },

"dependencies": { "jaws-core-js": "~0.0.2", + "request": "^2.65.0" }

81

npm install 時に実行されるコマンドjaws postinstall コマンドが JAWSプロジェクトのaws-modulesディレクトリにawsmフォルダ内のファイルをコピーする。

依存モジュールも忘れずに。

Page 82: AWSで作る サーバレスAPIアプリケーション

NPMに公開$ npm publish

$ npm install https://github.com/bisque33/awsm-github-webhook --save

82

このサンプルは、実際にはnpmでは公開していません。

試してみたい場合は、Githubからinstallしてください。

https://github.com/bisque33/awsm-github-webhook

Page 83: AWSで作る サーバレスAPIアプリケーション

AWSMをプロジェクトにインポートする

83

Page 84: AWSで作る サーバレスAPIアプリケーション

AWSMのインポート・デプロイ$ npm install [awsm_name] --save

$ jaws env set [stage] [region] [変数名] [値]

$ jaws deploy resource

$ jaws dash

[JAWS] AWSMを使って認証・認可APIを作る | Developers.IO

http://dev.classmethod.jp/server-side/framework/jaws-awsm-users/

84

AWSMのダウンロード

環境変数の設定(必要があれば)

LambdaとAPI Gatewayのデプロイ

リソースのデプロイ(必要があれば)

Page 85: AWSで作る サーバレスAPIアプリケーション

まとめ

85

Page 86: AWSで作る サーバレスAPIアプリケーション

まとめ• インフラからデプロイまで、実際のアプリケーションを開発する上で不足している部分を補ってくれて便利!

• AWSMはnpmにして再利用可能にしよう!• まだベータなのでご利用は慎重に!

86

Page 87: AWSで作る サーバレスAPIアプリケーション

参考• jaws-framework/JAWS

https://github.com/jaws-framework/JAWS

• (DVO209) JAWS: A Scalable Serverless Frameworkhttp://www.slideshare.net/AmazonWebServices/dvo209-jaws-a-scalable-serverless-framework

• (レポート) DVO209: JAWS: 高度にスケーラブルなサーバーレスフレームワーク #reinvent | Developers.IOhttp://dev.classmethod.jp/cloud/aws/reinvent2015-dvo209/

• JAWSフレームワークで、サーバレスな分散ロックサービス「Joumae」をつくった - Qiita http://qiita.com/mumoshu/items/3cbe31b315be31f510d0

87

Page 88: AWSで作る サーバレスAPIアプリケーション

ご静聴ありがとうございました。