サーバーレスアプリケー
ションの作り方
株式会社エクストーン
豊田陽一
今日のお話
• AWS Serverless Application Model (SAM)のお話
• さっくりと環境構築
• 開発してみる
• 手元で動かしてみる
• デプロイしてみる
AWS Serverless Application Model
• サーバーレスアプリケーションを構築するためのフレームワー
ク
• AWS Lambda
• イベントソース
• S3, DynamoDB
• SNS
• CloudFront
• API Gateway
• etc.
• データベース
SAM-CLI
• サーバーレスアプリケーション
を構築するためのコマンドライ
ンインターフェイス
• 初期化
• パッケージ化
• ローカル実行
• デプロイ
• 前提準備
• docker
• aws-cli
• python (pip)
$ pip install awscli
$ pip install aws-sam-cli
$ sam init --runtime nodejs8.10
$ tree
.
├── hello_world
│ ├── app.js
│ ├── package.json
│ └── tests
│ └── unit
│ └── test_handler.js
├── README.md
└── template.yaml
template.yml
• サーバーレスアプリケーションの定義
ファイル
• リソース
• Lambda関数
• イベントソース
• データベース
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: hello_world/
Handler: app.lambdaHandler
Runtime: nodejs8.10
Environment
Variables:
PARAM1: VALUE
Events:
HelloWorld:
Type: Api
Properties:
Path: /hello
Method: get
Lambda function (app.js)
• サンプルで作られる関数
• IP調べるAWSのAPI叩く
• 結果をJSONで返す
• 返り値のフォーマットはAPI
Gatewayに合わせてある
const axios = require('axios')
const url = 'http://checkip.amazonaws.com/';
let response;
exports.lambdaHandler =
async (event, context) => {
try {
const ret = await axios(url);
response = {
'statusCode': 200,
'body': JSON.stringify({
message: 'hello world',
location: ret.data.trim()
})
}
} catch (err) {
console.log(err);
return err;
}
return response
};
ローカル実行
• sam local
• ローカル環境でサーバーレスア
プリケーションの実行が可能
• dockerを利用して動作
• 実行する単位
• sam local start-api
• APIとしてサーバーを起動
• sam local start-lambda
• Lambda関数としてサーバーを起
動
• sam local invoke
• その場で実行
$ sam local start-api
2018-12-14 11:32:52 Mounting
HelloWorldFunction at
http://127.0.0.1:3000/hello [GET]
2018-12-14 11:32:52 You can now browse to the
above endpoints to invoke your functions. You
do not need to restart/reload SAM CLI while
working on your functions changes will be
reflected instantly/automatically. You only
need to restart SAM CLI if you update your
AWS SAM template
2018-12-14 11:32:52 * Running on
http://127.0.0.1:3000/ (Press CTRL+C to quit)
$ curl.exe http://127.0.0.1:3000/hello
{"message":"hello
world","location":"210.172.0.33"}
実行時パラメータのサンプル生成
• 様々なイベントソースから
lambdaが呼び出されたときのパ
ラメータを自動生成できる
• sam local invokeに渡す
$ sam local generate-event
…
Commands:
alexa-skills-kit
alexa-smart-home
apigateway
batch
cloudformation
cloudfront
cloudwatch
codecommit
codepipeline
cognito
config
dynamodb
kinesis
lex
rekognition
s3
ses
sns
sqs
stepfunctions
パッケージング
• sam package
• パッケージ化とS3へのアップ
ロード
• ファイルの配置先が記述してあ
るデプロイ用のテンプレート
ファイルを生成する
• 実体は aws cloudformation
package コマンド
$ aws s3 mb s3://<s3-bucket-name>/
$ sam package --template-file template.yaml 
--output-template-file output.yaml 
--s3-bucket <s3-bucket-name>
Uploading to 94e3fd6b94ae265626525b73593b09f7
943136 / 943136.0 (100.00%)
Successfully packaged artifacts and wrote
output template to file output.yaml.
Execute the following command to deploy the
packaged template
aws cloudformation deploy --template-file
/home/wiste/sam-test/sam-app/output.yaml --
stack-name <YOUR STACK NAME>
デプロイ
• sam deploy
• AWS CloudFormationのスタック
を作成(更新)し、サーバーレス
アプリケーションを構築する
$ sam deploy 
--template-file output.yaml 
--stack-name hello-world-sam
--capabilities CAPABILITY_IAM
Waiting for changeset to be created..
Waiting for stack create/update to complete
Successfully created/updated stack - hello-
world-sam
Rubyでも書けます
• sam init
• runtimeにruby2.5を指定する
• sam-cli 0.9.0で確認
• sam-cliが古いとruby2.5が指定できな
い
• サンプルはJS版と一緒
• HTTP ClientはHTTPartyだった
• When you HTTParty, you must party
hard!
$ sam init --name hello-world-ruby-app 
--runtime ruby2.5
$ tree
.
├── Gemfile
├── hello_world
│ └── app.rb
├── README.md
├── template.yaml
└── tests
└── unit
└── test_handler.rb
まとめ
• sam-cliのお話
• サーバーレスアプリケーション用のフレームワーク
• Lambdaのコード
• イベントソース
• CloudFormationを利用したスタックの作成
• sam packageによるパッケージ化
• sam deployによるデプロイ
• Lambda周りのコード管理やデプロイもこれで解決!

サーバーレスアプリケーションの作り方

  • 1.
  • 2.
    今日のお話 • AWS ServerlessApplication Model (SAM)のお話 • さっくりと環境構築 • 開発してみる • 手元で動かしてみる • デプロイしてみる
  • 3.
    AWS Serverless ApplicationModel • サーバーレスアプリケーションを構築するためのフレームワー ク • AWS Lambda • イベントソース • S3, DynamoDB • SNS • CloudFront • API Gateway • etc. • データベース
  • 4.
    SAM-CLI • サーバーレスアプリケーション を構築するためのコマンドライ ンインターフェイス • 初期化 •パッケージ化 • ローカル実行 • デプロイ • 前提準備 • docker • aws-cli • python (pip) $ pip install awscli $ pip install aws-sam-cli $ sam init --runtime nodejs8.10 $ tree . ├── hello_world │ ├── app.js │ ├── package.json │ └── tests │ └── unit │ └── test_handler.js ├── README.md └── template.yaml
  • 5.
    template.yml • サーバーレスアプリケーションの定義 ファイル • リソース •Lambda関数 • イベントソース • データベース Resources: HelloWorldFunction: Type: AWS::Serverless::Function Properties: CodeUri: hello_world/ Handler: app.lambdaHandler Runtime: nodejs8.10 Environment Variables: PARAM1: VALUE Events: HelloWorld: Type: Api Properties: Path: /hello Method: get
  • 6.
    Lambda function (app.js) •サンプルで作られる関数 • IP調べるAWSのAPI叩く • 結果をJSONで返す • 返り値のフォーマットはAPI Gatewayに合わせてある const axios = require('axios') const url = 'http://checkip.amazonaws.com/'; let response; exports.lambdaHandler = async (event, context) => { try { const ret = await axios(url); response = { 'statusCode': 200, 'body': JSON.stringify({ message: 'hello world', location: ret.data.trim() }) } } catch (err) { console.log(err); return err; } return response };
  • 7.
    ローカル実行 • sam local •ローカル環境でサーバーレスア プリケーションの実行が可能 • dockerを利用して動作 • 実行する単位 • sam local start-api • APIとしてサーバーを起動 • sam local start-lambda • Lambda関数としてサーバーを起 動 • sam local invoke • その場で実行 $ sam local start-api 2018-12-14 11:32:52 Mounting HelloWorldFunction at http://127.0.0.1:3000/hello [GET] 2018-12-14 11:32:52 You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions changes will be reflected instantly/automatically. You only need to restart SAM CLI if you update your AWS SAM template 2018-12-14 11:32:52 * Running on http://127.0.0.1:3000/ (Press CTRL+C to quit) $ curl.exe http://127.0.0.1:3000/hello {"message":"hello world","location":"210.172.0.33"}
  • 8.
    実行時パラメータのサンプル生成 • 様々なイベントソースから lambdaが呼び出されたときのパ ラメータを自動生成できる • samlocal invokeに渡す $ sam local generate-event … Commands: alexa-skills-kit alexa-smart-home apigateway batch cloudformation cloudfront cloudwatch codecommit codepipeline cognito config dynamodb kinesis lex rekognition s3 ses sns sqs stepfunctions
  • 9.
    パッケージング • sam package •パッケージ化とS3へのアップ ロード • ファイルの配置先が記述してあ るデプロイ用のテンプレート ファイルを生成する • 実体は aws cloudformation package コマンド $ aws s3 mb s3://<s3-bucket-name>/ $ sam package --template-file template.yaml --output-template-file output.yaml --s3-bucket <s3-bucket-name> Uploading to 94e3fd6b94ae265626525b73593b09f7 943136 / 943136.0 (100.00%) Successfully packaged artifacts and wrote output template to file output.yaml. Execute the following command to deploy the packaged template aws cloudformation deploy --template-file /home/wiste/sam-test/sam-app/output.yaml -- stack-name <YOUR STACK NAME>
  • 10.
    デプロイ • sam deploy •AWS CloudFormationのスタック を作成(更新)し、サーバーレス アプリケーションを構築する $ sam deploy --template-file output.yaml --stack-name hello-world-sam --capabilities CAPABILITY_IAM Waiting for changeset to be created.. Waiting for stack create/update to complete Successfully created/updated stack - hello- world-sam
  • 11.
    Rubyでも書けます • sam init •runtimeにruby2.5を指定する • sam-cli 0.9.0で確認 • sam-cliが古いとruby2.5が指定できな い • サンプルはJS版と一緒 • HTTP ClientはHTTPartyだった • When you HTTParty, you must party hard! $ sam init --name hello-world-ruby-app --runtime ruby2.5 $ tree . ├── Gemfile ├── hello_world │ └── app.rb ├── README.md ├── template.yaml └── tests └── unit └── test_handler.rb
  • 12.
    まとめ • sam-cliのお話 • サーバーレスアプリケーション用のフレームワーク •Lambdaのコード • イベントソース • CloudFormationを利用したスタックの作成 • sam packageによるパッケージ化 • sam deployによるデプロイ • Lambda周りのコード管理やデプロイもこれで解決!