Recently I have been working on some AWS Lambda functions, and I am using the serverless framework to help build and deploy them. However, once I wanted to have multiple stages with different environment variables I was not sure the best way to do it. Here are some things I tried and the command I ended up going with in the end.
Initially I tried implementing a solution similar to the one found in this article. Initially, I thought, "wow, this is excellent because all I have to do is use the '--stage' flag and my environment variables will be taken care of for me since they are included as custom variables in the serverless.yaml config file". However, for some reason when I deployed my variables would never show up in the AWS Lambda console, and more importantly they weren't being loaded into the functions when they were run!
After some digging into forums and stack overflow posts the only working solution I was able to come up with was to use the serverless-dotenv-plugin. This nifty little npm package allows you to send a "--env" flag with your serverless commands and it will read from that corresponding .env.<environment> file. The annoying thing here is that you need to have a bunch of these .env files for each environment, but I guess it's probably safer to have your secret keys in there than being pushed up to git in your serverless.yaml file.
With the serverless-dotenv-plugin we need to pass the "--env" flag, and this is to specify from which .env file we want it to pull the environment variables. Although the "--stage" flag is no longer needed for environment variables, the serverless framework by default concatenates it onto the end of the function name and uses it for a few other things so I like to pass it in as a command line flag. So, Here are examples of how I would run serverless commands with this setup:
^ Deploys function to AWS with environment variables located in the .env.prod file.
^ Starts a local server hosting your lambda functions with environment variables from .env.local file.
The posts on this site are written and maintained by Jim Lynch. About Jim...
Want FREE access to
my daily stock tips
Sign up here:
- Triple Gainers
- Rippers N' Dippers
- Growingest Growers