Serverless Stage Environment Variables Plugin
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 8.x or higher runtime required.
Usage
Define a custom.stageEnvVars
object inside your Serverless config, and specify the default environment and a path the environment configuration file.
This configuration is required.
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.` // BU: This will be dynamic based on the slice name, won't it? CERTIFICATE_COMMON_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)/moduleexports = 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.