Lambdaの使い方 - ローカルで開発・実行・デプロイまで[nodejs編]
日本語 | English
概要
AWSサービスのLambda入門メモ。
S3にある指定ファイルの内容を返すイベントを作る。
Lambdaは node 4.3
を使う。
開発コード
package.json
・・・ aws-sdk インストール
{ "name": "application-name", "version": "1.0.0", "description": "application description", "main": "application.js", "scripts": { "test": "node local_run.js" }, "author": "", "dependencies": { "aws-sdk": "^2.4.13" } }
$ npm install
しましょう
local_run.js
・・・ ローカル実行の着火ファイル
(http://lambda-url/function-name?key=test の例)
'use strict' // Your data to be passed to lambda function let event = { key: 'test' } // Build stab of context Object let context = { functionName: 'function-name', invokeid: 'invokeid', done: function(err, message) { return; }, succeed: function(message) { console.log(message) } } let app = require('./application.js') app.handler(event, context)
application.js
・・・ 実際にアップするファイル
'use strict'; const AWS = require('aws-sdk') AWS.config.update({ accessKeyId: '', secretAccessKey: '', region: 'ap-northeast-1', endpoint: 'https://s3-ap-northeast-1.amazonaws.com' }) const s3client = new AWS.S3() exports.handler = (event, context) => { let params = { Bucket: "hogehoge", Key: event.key } s3client.getObject(params, (err, data) => { if (data != null) { context.succeed(data.Body.toString()) } }) }
ローカル実行
$ node local_run.js
をたたく。
デプロイ用zip作成、アップロード
$ zip -r testfunc.zip application.js node_modules
で、できた testfunc.zip
をコンソールからアップする。
コンソール > lambda > 指定function の Configuration で
Handler
をapplication.handler
にして
他は適宜設定。