LoginSignup
0
1

More than 3 years have passed since last update.

node.jsとserverlessでローカル環境のコードをlambdaにアップする

Last updated at Posted at 2020-12-01

はじめに

node.jsで作成したアプリをサーバーレスで動かしたい。

環境

node.js v12.18.2

Lambda関数の作成

ディレクトリ作成

mkdir serverless-node-sample
cd serverless-node-sample

npmの初期化

npm init

Serverlessのインストール

npm install serverless --save

Serverlessの動作確認

バージョン確認

sls -v

以下のように表示されればOK

Framework Core: 2.13.0 (local)
Plugin: 4.1.2
SDK: 2.3.2
Components: 3.4.2

Serverlessのテンプレート生成

今回はnode.jsを使うので aws-nodejsを使用、他にもpythonやruby用のテンプレートが用意されている
コマンド実行後、handler.js serverless.yml .gitignoreが生成される

serverless create --template aws-nodejs

ディレクトリ構成の確認

確認

ls -a

きっとこうなっているはず

.                       .gitignore              node_modules            package.json
..                      handler.js              package-lock.json       serverless.yml

ローカルでの動作確認

今回のメインファイルとなるhandler.jsの中身を確認。
うまくいけばGo Serverless v1.0! Your function executed successfully!が表示するはず。


'use strict';

module.exports.hello = async event => {
  return {
    statusCode: 200,
    body: JSON.stringify(
      {
        message: 'Go Serverless v1.0! Your function executed successfully!',
        input: event,
      },
      null,
      2
    ),
  };

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

早速コマンドから実行する。
sls invoke はデプロイされた関数を呼び出すコマンド、sls invoke localにしてあげると、ローカル環境で関数を呼び出す。

sls invoke local --function hello

おお、表示された

Serverless: Running "serverless" installed locally (in service node_modules)
{
    "statusCode": 200,
    "body": "{\n  \"message\": \"Go Serverless v1.0! Your function executed successfully!\",\n  \"input\": \"\"\n}"
}

AWSにアクセスするための設定

AWSにアクセスするコマンドを叩く。
aws_access_key_id aws_secret_access_keyはお手持ちのAWSアカウントから取得してもらえれば。

serverless config credentials --provider aws --key aws_access_key_id --secret aws_secret_access_key
補足:IAM ユーザーのアクセスキーとクレデンシャル情報の取得

AWSマネジメントコンソールの「サービスを検索する」という入力欄で「IAM」と入力すればIAMダッシュボードのページに飛びます。ページアクセス後はサイドバーのアクセス管理のタブからユーザーをクリック。あとはユーザーを追加して新しくアクセスキーを作成するもよし、既存のユーザーから取得するもよし。(詳しくはこちら

AWSに関数をデプロイ

以下のコマンドでデプロイは完了
regionオプションはAWSの東京リージョンにアップするよっていう指定をしてくれる。

serverless deploy --region ap-northeast-1

デプロイした関数を実行

sls invoke --function hello --data Hello --region ap-northeast-1

先ほどと同じ結果が帰ってきていればOK

{
    "statusCode": 200,
    "body": "{\n  \"message\": \"Go Serverless v1.0! Your function executed successfully!\",\n  \"input\": \"Hello\"\n}"
}

以上です、やったぜ。

0
1
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
1