Serverless Environment Variables

Mirza Joldic
Dec 30, 2016 · 3 min read
$ serverless -v
1.4.0
$ mkdir serverless-environment-variables
$ cd serverless-environment-variables
# serverless.yml
service: serverless-environment-variables
provider:
name: aws
runtime: nodejs4.3
functions:
hello:
handler: handler.hello
// handler.js
'use strict';
module.exports.hello = (event, context, callback) => {
const response = {
foo: 'bar',
};
callback(null, response);
};
$ serverless invoke local -f hello
{
"foo": "bar"
}
# serverless.yml
service: serverless-environment-variables
provider:
name: aws
runtime: nodejs4.3
environment:
MY_VAR: abc
functions:
hello:
handler: handler.hello
// handler.js
'use strict';
module.exports.hello = (event, context, callback) => {
const response = {
foo: 'bar',
MY_VAR: process.env.MY_VAR,
};
callback(null, response);
};
$ serverless invoke local -f hello
{
"foo": "bar",
"MY_VAR": "abc"
}
# serverless.env.yml
dev:
SECRET_VAR: 'secret in dev'
# serverless.yml
service: serverless-environment-variables
provider:
name: aws
runtime: nodejs4.3
environment:
MY_VAR: abc
SECRET_VAR: ${file(./serverless.env.yml):dev.SECRET_VAR}
functions:
hello:
handler: handler.hello
// handler.js
'use strict';
module.exports.hello = (event, context, callback) => {
const response = {
foo: 'bar',
MY_VAR: process.env.MY_VAR,
SECRET_VAR: process.env.SECRET_VAR,
};
callback(null, response);
};
$ sls invoke local -f hello
{
"foo": "bar",
"MY_VAR": "abc",
"SECRET_VAR": "secret in dev"
}
# serverless.env.yml
dev:
SECRET_VAR: 'secret in dev'
prd:
SECRET_VAR: 'secret in prd'
# serverless.yml
service: serverless-environment-variables
provider:
name: aws
runtime: nodejs4.3
environment:
MY_VAR: abc
SECRET_VAR: ${file(./serverless.env.yml):${opt:stage}.SECRET_VAR}
functions:
hello:
handler: handler.hello
$ sls invoke local -f hello -s dev
{
"foo": "bar",
"MY_VAR": "abc",
"SECRET_VAR": "secret in dev"
}
$ sls invoke local -f hello -s prd
{
"foo": "bar",
"MY_VAR": "abc",
"SECRET_VAR": "secret in prd"
}

Mirza Joldic

Written by

Javascript enthusiast & full stack dev. Amateur musician & artist. Aspiring homesteader.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade