Node.js+Serverless+AWSでお手軽サーバレスアプリを作る: 事前準備
Serverlessフレームワークをもちると、手軽にサーバレスアプリを構築することができます。 今回はNode.js v12 と AWSをもちいてサーバレスアプリを作る事前準備について説明します。
The Serverless Application Framework | Serverless.com
Serverlessアプリケーションの作成
AWS上にNode.jsのServerlessアプリケーションを作成するには以下のコマンドで作成できます。
mkdir sls-sample $ npm install -g serverless $ sls create --template aws-nodejs
handler.js, serverless.yml の2つが作成されます。
API経由でLambda関数が動作するようにする
初期の設定だとLambda関数とHttpイベントが紐付いていないので serverless.ymlを開いてコメントアウトされているHttpイベントの部分を以下の様にコメント外します。
functions:
hello:
handler: handler.hello
# The following are a few example events you can configure
# NOTE: Please make sure to change your handler code to work with those events
# Check the event documentation for details
events:
- http:
path: users/create
method: get
AWS認証情報の設定
AWSのWebコンソール上でIAMユーザを作成してAdministrator Accessのポリシーをアタッチします。
AWS アカウントでの IAM ユーザーの作成 - AWS Identity and Access Management
次に、以下のリンクを参考にローカル環境にAWSの認証情報を設定します。
これでローカル環境からすべてのAWSサービスの操作ができるようになります。
デプロイ
以下のコマンドを実行することで、Serverlessアプリケーションがデプロイされます。
$ sls deploy
ServerlessアプリケーションはAWSではCloudFormationとしてデプロイされます。
sls deployの出力結果は以下のようになっています。
Service Information service: sls-sample stage: dev region: us-east-1 stack: sls-sample-dev resources: 12 api keys: None endpoints: GET - https://xxx.execute-api.us-east-1.amazonaws.com/dev/users/create functions: hello: sls-sample-dev-hello layers: None
ここに表示されている GET - https://xxx.execute-api.us-east-1.amazonaws.com/dev/users/create を実際にリクエストしてみます。
$ curl https://xxx.execute-api.us-east-1.amazonaws.com/dev/users/create
{
"message": "Go Serverless v1.0! Your function executed successfully!",
"input": {
"resource": "/users/create",
"path": "/users/create",
"httpMethod": "GET",
"headers": {
...
handler.jsの内容を実行することができました。