Skip to content
This repository has been archived by the owner on Sep 3, 2024. It is now read-only.

A Serverless Framework plugin for using stage-specific environment variables

License

Notifications You must be signed in to change notification settings

digio/serverless-stage-env-vars

Repository files navigation

Serverless Stage Environment Variables Plugin

serverless npm package Build Status Coverage Status Downloads

A Serverless plugin to easily use stage-specific environment variables.

Installation

npm install --save-dev serverless-stage-env-vars

Add the plugin to serverless.yml:

plugins:
  - serverless-stage-env-vars

Note: Node 10.x or higher runtime required.

Usage

Inside your Serverless config, include this plugin and define a custom.stageEnvVars object and specify the default environment and a path the environment configuration file. This configuration is required.

plugins:
  - serverless-stage-env-vars
  ...

custom:
  stageEnvVars:
    defaultEnv: dev # The name of the stage config to use if no matching stage is found
    environmentFile: path/relative/to/cwd/config.js

Next, define your environment config file (e.g. path/relative/to/cwd/config.js):

// This config file is designed to contain configuration that is needed by
// APIs and websites. This config is global in nature.
const BASE_DOMAIN_NAME = 'foo.digio.com.au';

const devConfig = {
  AWS_ACCOUNT_ID: 'devAccountId',
  WEB_DOMAIN: `plugin.${BASE_DOMAIN_NAME}`,
  CERTIFICATE_COMMON_NAME: `*.${BASE_DOMAIN_NAME}`,
  TRACING_ENABLED: false,
};

// Export a configuration object which has top-level properties which match
// the Serverless stage names you use.
// If a matching stage name is not found, the Serverless custom.stageEnvVars.defaultEnv config
// will be used (which is 'dev' in this example)/
module.exports = {
  dev: { ...devConfig },
  prod: {
    ...devConfig,
    AWS_ACCOUNT_ID: 'prodAccountId',
    TRACING_ENABLED: true,
  },
};

Finally, you can refer to stage environment variables in your Servlerless config file using the ${stageEnv:VARIABLE_NAME} syntax:

provider:
  environment:
    XRAY_ENABLED: '${stageEnv:TRACING_ENABLED}'
    AWS_ACCOUNT_ID: '${stageEnv:AWS_ACCOUNT_ID}'
    ...
  tracing:
    apiGateway: '${stageEnv:TRACING_ENABLED}',
    lambda: '${stageEnv:TRACING_ENABLED}',

The plugin will replace those variables with the stage-specific values from your environment-config file.

About

A Serverless Framework plugin for using stage-specific environment variables

Resources

License

Stars

Watchers

Forks

Packages

No packages published