LoginSignup
0
2

More than 5 years have passed since last update.

amazon linux 上に serverless framework 開発環境構築

Last updated at Posted at 2017-07-09

EC2インスタンスを Amazon Linux (AMI)で立ち上げて、serverless framework の開発環境を作ります。

sshでec2インスタンスに接続するところまでは、省略。

nodejsの導入

nvm経由でnodejsを導入します。

yumでは、nodejs見つからず
$ yum search nodejs
Loaded plugins: priorities, update-motd, upgrade-helper
Warning: No matches found for: nodejs
No matches found

nvmをインストールします。amazonのTutorialに記載されているコマンドは、nvmのバージョンがv0.32.0と古いので、本家サイトに記載のコマンドを実行。

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.2/install.sh | bash

環境変数、PATH設定等を行う為の処理が、.bashrcに追記されていることを確認し、反映します。

source ~/.bash_profile

以下のような処理が'.bashrc'追記されます。

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

lambaのnodejs環境は、v6.10 (2017/6/2時点)ですので、v6.10をインストールします。
なおlambda@edge環境に配置する場合は、v4.3にします。

# v6.10系があることを確認
nvm ls-remote
# v6.10をインストール(v6.10.3が最新)
nvm install v6.10
# v6.10を使用開始
nvm use 6.10

インストールされたことを確認します。

$ node -e "console.log('Running Node.js ' + process.version)"
Running Node.js v6.10.3
$ node -v
v6.10.3

serverless frameworkのインストール

serverless framework をインストールします。
https://serverless.com/framework/docs/providers/aws/guide/installation/

npm install -g serverless

インストールされたことを確認します。

$ serverless --version
1.14.0
$ sls --version
1.14.0

serverless framework を使って、lambda functionを作成してみます。
serverless では、lambdaで利用可能な言語環境をtemplateとして指定し、functionを作成していきます。
以下のコマンドを実行します。

sls create --template aws-nodejs --path chat

handler.js, serverless.ymlの2ファイルが作成されます。
aws上のサービスを定義するserverlessの定義ファイルも含めて作成されています。

単純なメッセージを返すfunctionのhelloが作成されているので、ローカルで動作させてみます。

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

実行されたfunctionのhelloは、handler.jsに実装されています。

handler.js
'use strict';

module.exports.hello = (event, context, callback) => {
  const response = {
    statusCode: 200,
    body: JSON.stringify({
      message: 'Go Serverless v1.0! Your function executed successfully!',
      input: event,
    }),
  };

  callback(null, response);

  // Use this code if you don't use the http event with the LAMBDA-PROXY integration
  // callback(null, { message: 'Go Serverless v1.0! Your function executed successfully!', event });
};

補足

Serverless Framework のコマンドでのエラーが発生した時、エラーの詳細を知りたくなります。
エラー詳細に出力させる場合は、以下の環境変数を設定してください。

export SLS_DEBUG=true
0
2
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
0
2