Skip to content

Andrew Birck's Blog

Environment variables in serverless

March 05, 2020

I’ve been playing around with a Node service on AWS Lambda and got to the point where I needed to use two different keys cross several different functions all defined within a single serverless yaml file. One for my dev environment and one for production. I figured setting that up would be easy but I had to search through quite a few articles before I found something that worked.

In case anyone else runs into the same problem here’s what I found to be a fairly simple solution.

The serverless yaml file changes

I had to add a custom section to the file that defined the stage that was being deployed to so that I could reference it later:

custom:
stage: ${opt:stage, self:provider.stage}

Then under provider I defined an environment property and told it which json file to load to get the environment variables based on the stage:

provider:
name: aws
runtime: nodejs10.x
stage: dev
region: us-west-2
environment: ${file(./${self:custom.stage}.env.json)}

Define the files (and don’t forget to add *.env.json to your .gitignore if they have secrets):

dev.env.json

{
"LIBRARY_SECRET_KEY": "<dev secret key>"
}

prod.env.json

{
"LIBRARY_SECRET_KEY": "<prod secret key>"
}

Node file changes

Then the javascript code just needs to be updated to read values from process.env. Here’s an example where a secret key is passed in to a library to initalize it:

const lib = require("mylibrary")(process.env.LIBRARY_SECRET_KEY)

Conclusion

The above steps got things working for me. If you’re in a similar situation hopefully you’ll find them useful too.


Andrew Birck
A place to for me to post stuff (mostly)
about software development.