LoginSignup
0
0

More than 1 year has passed since last update.

serverless FWの細かい設定 stageとcustomを使った外部ファイルでの環境変数設定

Posted at

はじめに

serverlessアプリケーションを開発する上で便利なserverlessにおける、ちょっとしたTipsを備忘録として残しておこうと思う。

※今後も随時追記していく予定。

serverless の細かい設定

stage

環境を分けるためにある機能
以下のようにopt:stage(CLI のオプションで渡ってきた値(ex) --stage dev))、self:custom.defaultStage(yaml の custom に定義している defaultStage の値)などを利用して設定可能

serverless.yaml
provider:
  stage: ${opt:stage, self:custom.defaultStage}

custom:
  defaultStage: local

functions:
  hello:
    name: hello-lambda-${self:provider.stage}

また、Referencing Serverless Core Variablesに書かれている通り、以下のように${sls:stage}というのも利用でき、これは${opt:stage, self:provider.stage, "dev"}の省略記法になる。

serverless.yaml
provider:
  stage: local

functions:
  hello:
    name: hello-lambda-${sls:stage}

上記のように設定した場合、CLIのオプションで--stage sandboxのように指定されたら、Lambda関数の名前はopt:stageが適用され、hello-lambda-sandboxになる。
もし何も指定しなければ、opt:stageがないので次のself:provider.stageが適用され、Lambda関数の名前はhello-lambda-localになる。
仮にprovider.stageがserverless.yamlに未定義の場合には、最後の項目であるdevが適用され、Lambda関数の名前はhello-lambda-devになる。

ソースコード全体は以下。

custom

Reference Properties In serverless.ymlに書かれているように、customはserverless.yaml内で独自に使用したい値を定義できる項目になる。このcustomを利用して、各stageごとに環境変数の設定を変えるなんて事もできる。

例えば以下のようにserverless.yamlを記述すると、stage名に対になるように作成されているjsonファイルのキーを設定する事で、Lambda関数に環境変数を設定できる。

serverless.yaml
# 省略
provider:
  stage: ${opt:stage, self:custom.defaultStage}
  # 省略

# 省略

custom:
  defaultStage: local
  environment:
    local: ${file(./env/local.json)}
    development: ${file(./env/development.json)}
    staging: ${file(./env/staging.json)}
    production: ${file(./env/production.json)}
  # 省略

functions:
  hello:
    # 省略
    environment:
      ENV: ${self:custom.environment.${self:provider.stage}.ENV}

study@localhost:~/workspace/learn-serverless (main *)
$ tree -I node_modules
.
...
├── env
│   ├── development.json
│   ├── local.json
│   ├── production.json
│   └── staging.json
...
├── serverless.yml
...

ファイルの読み込みに関してはRecursively reference propertiesなどの章が参考になる。上記のように設定する事で、stageの値に応じて各jsonの中に定義されているENVというキーの値を、Lambda関数のenvironmentとして設定する事ができる。

※serverless.yamlの書き方に関しては好みの問題になるかもしれないが、Recursively reference propertiesにある書き方を真似するのであれば、以下のように書く事もできるだろう。

serverless.yaml
functions:
  hello:
    # 省略
    environment:
      ENV: ${file(./env/${self:provider.stage}.json):ENV}

ソースコード全体は以下。

まとめとして

今回取り上げたstageやcustomを使った外部ファイルからの環境変数設定はちょっとしたTipsだが、実際にアプリケーションを開発・運用していく上では有益な機能に思える。

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