LoginSignup
0
2

More than 5 years have passed since last update.

Serverlessでnode-configを使う

Last updated at Posted at 2016-11-19

v1.2から環境変数設定ができるようです(2016/11/22 追記)

コメントにもあるように、Lambdaが環境変数をサポートしました。
Serverlessでも環境変数をサポートし、以下のような設定ができます。

serverless.yml
service: environment-variables

provider:
  environment:
    provider_level: provider
  name: aws
  runtime: nodejs4.3
  cfLogs: true

functions:
  hello:
    environment:
      FUNCTION_LEVEL: function
    handler: handler.hello
    events:
      - http:
          integration: lambda
          path: hello
          method: get
現時点ではまだこの機能はリリースされていません。v1.2でサポートされるようです。

(2016/11/23 1:12 追記)
v1.2.0がリリースされました:tada:
v1.2.0から環境変数サポートされたのでdotenvを利用する必要はなくなりました。

結論

設定方法

dev環境での実行を想定します。

1. dotenvを使ってNODE_ENVを設定する

.envNODE_ENV=devを設定します。

NODE_ENV=dev

2. node-configで利用する環境ごとのファイルを用意する

node-configでdevの設定を利用するために./config/dev.jsを用意します

./config/dev.js
module.exports = {
  db: {
    host: "dev.example.com",
    user: "dev_user",
    pass: "dev_pass",
  }
};

3. dotenvとconfigをrequireする

require("dotenv").configをするとNODE_ENV=devが環境変数に設定されます。
設定後にnode-configを呼び出すことでdevの設定が利用できるようになります。

sample.js
require("dotenv").config;

const config = require("config");

const db = require("db");
db.connect({
  host: config.db.host,
  username: config.db.user,
  password: config.db.pass
});
0
2
2

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
2