LoginSignup
7
7

More than 5 years have passed since last update.

Twilioサーバーレス化作業記録 - Token生成サーバーレス化

Last updated at Posted at 2015-12-17

はじめに

Twilioサーバーレス化作業メモです。
今回はCapabilityTokenを取得するためのAPIをAWS API GatewayとLambdaで作成します。

スクリプト生成

適当な場所に作業用フォルダを作成します。
そこにnpmにてtwilioインストール。

$ npm install twilio

index.js作成。

index.js
console.log('Loading function');

exports.handler = function(event, context) {
    var twilio = require("twilio");
    var capability = new twilio.Capability('myAccountSid', 'myAuthToken');
    capability.allowClientOutgoing('myAppSid');
    var token = capability.generate();

    console.log('token =', token);
    context.succeed(token);
};

コマンドラインでzip作成。

$ zip -r twilio.zip index.js node_modules/

AWS Lambda側

「Create a Lambda Function」にて新規作成。
blueprint選択せずskip。

Nameは「TwilioGenerateToken」としました。
Roleは「lambda_basic_execution」を選択。

作成後、「Code」タブ「Upload a .ZIP file」から先ほど作成したzipファイルをアップロードします。
Test実行して結果を確認しておきましょう。

注意:

はじめ、index.jsへのアクセス権限が制限されていたことでスクリプト実行に失敗していました。

EACCES, permission denied '/var/task/index.js

今回はFinderの「情報を見る」「共有とアクセス権」でEveryoneに「読み出しのみ」を設定しました。

API Gateway側

prodを新しいタブで開く
ページ上の右タブResourcesへ

Method Request

Method Execution の AuthenticationをNONE

Integration Request

  • Mapping Templates を選択
  • Content-Type を application/json

Input Path ThroughからMapping template へ変更。AWS lambdaに送ったパラメータを全て取得できるようにする

{
  "param": {
#foreach( $key in $input.params().querystring.keySet() )
    "$key": "$input.params().querystring.get($key)"#if( $foreach.hasNext ),#end
#end
  }
}

Integration Response

200を展開

Mapping Templates

  • Content-Type: application/json
  • Input Path ThroughからMapping Templateへ
#set($inputRoot = $input.path('$'))
$inputRoot

ここは...要再確認です。

Method Response

200を展開

Add Response Model

  • contenttype: application/json
  • Models: Empty

動作テスト

Testから叩いてみます。
Tokenが返却されました!

おわりに

Deployまで確認できませんでした。
サーバーレス化に邁進していきたい。

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7