0
0

More than 1 year has passed since last update.

Serverless Framework

Posted at

Serverless Framework とは、AWS などでサーバレスのサービスを作る手順を省略するツール。自分で CloudFormation を書くより簡単。よく似たツールとして AWS SAM というのもある。

インストール。開発に使う node と混ざるのが嫌なので standalone binary を選んだ (実際には node_modules があるとそちらを優先して使うようだ)。~/.serverless/bin にインストールされるので .zshrc の読み込みが必要。

curl -o- -L https://slss.io/install | bash

AWS 環境の選択。AWS_PROFILE や AWS_DEFAULT_REGION の region 設定は無視されデフォルトの region は us-east-1 になるので注意。

export AWS_PROFILE=hoge

ドキュメントの構成

ドキュメントは https://www.serverless.com/framework/docs にあるが構成がちょっと変だ。Serverless 全体の情報が AWS 固有の項目に混ざっている。例えば Variables はプロバイダに依存しない情報なのになぜか AWS 以下に置いてある。もしも AWS を使わない場合でも AWS のドキュメントに目を通す必要がある。

インタラクティブに単純な雛形を始める

サンプルの作成。例えば以下のように答えると単純な Node を使ったサンプルが作られる。

% serverless

 What do you want to make? AWS - Node.js - HTTP API
 What do you want to call this project? aws-node-http-api-project
 Do you want to login/register to Serverless Dashboard? No
 Do you want to deploy your project? No

プロジェクトディレクトリに移動してデプロイ

cd aws-node-http-api-project
serverless deploy

エンドポイントなどの情報を見てテスト

serverless info
curl https://ysr3am5c12.execute-api.us-east-1.amazonaws.com/

削除

serverless remove

その他の雛形を試す

インタラクティブに serverless を実行するとサンプルは https://github.com/serverless/serverless/blob/master/lib/cli/interactive-setup/service.js の中から選ばれる。他にも指定の方法は色々ある。

--template-url or -u:

serverless create -u https://github.com/serverless/examples/tree/master/aws-node-graphql-api-with-dynamodb -n graphql-dynamodb

現在エラーが出るので、serverless.yml を編集する。

runtime: nodejs14.x

デプロイ。

cd graphql-dynamodb
npm install
serverless deploy

テスト

curl -G https://mteoi3115k.execute-api.us-east-1.amazonaws.com/dev/query --data-urlencode 'query={greeting(firstName: "Jeremy")}'

--template or -t:

serverless create --template aws-nodejs-typescript --name aws-ts --path aws-ts
cd aws-ts
nvm use
npm install
serverless deploy
curl https://2nk6nw46bd.execute-api.us-east-1.amazonaws.com/dev/hello -H 'Content-Type: application/json' --data-raw '{ "name": "Frederic" }'

興味深い事にこれには serverless.ts のサンプルが含まれている。serverless.yml との違いは短く https://www.serverless.com/framework/docs/providers/aws/guide/intro で触れられている。

Variable

設定ファイル serverless.yml には以下のような変数を含める事が出来る。

  • ${variableSource}: 変数の一般的な参照方法。
  • ${variableSource, defaultValue}: デフォルト値の指定方法
  • ${file(ファイル名):KEY: JSON ファイルの指定方法。KEY の値に置き換わる。
  • ${self:KEY}: serverless.yml 内のキーの値を参照する。
  • ${sls:KEY}: Serverless 内部の変数を参照する。
  • ${env:KEY}: 環境変数を参照する。
  • ${opt:オプション}: コマンドラインオプションの参照 serverless deploy --オプション 値 のように渡す。
  • ${cf:stackName.outputKey}: CloudFromation output を参照する。

参考: https://www.serverless.com/framework/docs/providers/aws/guide/variables

参考

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