1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[serverless.yml] 複数の環境変数の設定でも楽がしたい!

Last updated at Posted at 2020-06-12

serverless.ymlで環境変数を環境ごとに設定するよくあるサンプル

まず、外部のファイルに環境変数を定義して、

conf/dev.yml
ENV_1: "dev"
ENV_2: "hoge"
ENV_3: "fuga"
 :
 :
ENV_100: "HENSU_TAKUSAN"

それをserverless.ymlで一つずつ読み込む

serverless.yml
provider:
  name: aws
  stage: ${opt:stage, self:custom.defaultStage}
  ... ランタイム周りの設定

custom:
  defaultStage: dev
  otherfile:
    environment:
      dev: ${file(./conf/dev.yml)}
      stg: ${file(./conf/stg.yml)}
      prod: ${file(./conf/prod.yml)}

functions:
  nanika:
    handler: nanika
    environment:
      ENV_1: ${self:custom.otherfile.environment.${self:provider.stage}.ENV1}
      ENV_2: ${self:custom.otherfile.environment.${self:provider.stage}.ENV2}
      ENV_3: ${self:custom.otherfile.environment.${self:provider.stage}.ENV3}
        :
        :
      ENV_100: ${self:custom.otherfile.environment.${self:provider.stage}.ENV100}

正直、環境変数が多いと、見づらいしコピペミスしそう。。

一つずつ設定しなくても、上記のconf/dev.ymlをそのまま使えないの??

conf/[dev|stg|prod].ymlをそのまま使う

環境変数を一つずつ設定する代わりに、ファイルをそのまま書けばOKだった。

serverless.yml
provider:
  name: aws
  region: ap-northeast-1
  stage: ${opt:stage, self:custom.defaultStage}

custom:
  defaultStage: dev
  otherfile:
    dev: ${file(./conf/dev.yml)}
    stg: ${file(./conf/stg.yml)}
    prod: ${file(./conf/prod.yml)}

functions:
  nanika:
    handler: nanika
    environment: ${self:custom.otherfile.${self:provider.stage}}

これで環境変数が100あってもconf/*.ymlを修正するだけでOK。

そもそも

多くの環境変数を使うこと自体よろしくないので、設定ファイルに書き出すなり、データストア使うなり、機密情報はKMSなどを使うのが良いのだけれども、プロトタイプをゴリゴリ描く時はこれで良いかも。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?