Posted on • Originally published atblog.neverendingqs.com
Using dotenv with the Serverless Framework
In myprevious post, I advised that theserverless-dotenv-plugin will no longer be able to load environment variables in time to resolveenv
variables in your service files (e.g.serverless.yml
). In this post, I want to go into details on how you can usedotenv
without the plugin.
With the Serverless Framework, you can use thefile
variable todynamically evaluate variables by executing JavaScript code. Leveraging this feature, you can get the Serverless Framework to run any arbitrary code, such as callingdotenv
to load environment variables! See howMY_ENV_VAR
is loaded into the framework below:
.env.local
:
MY_ENV_VAR=loaded-by-dotenv
configs.js
:
constdotenv=require('dotenv');module.exports=async({options,resolveConfigurationProperty})=>{// Load env vars into Serverless environment// You can do more complicated env var resolution with dotenv hereconstenvVars=dotenv.config({path:'.env.local'}).parsed;returnenvVars;};
serverless.yml
:
service:my-service# Required to use the new variables engine# https://www.serverless.com/framework/docs/providers/aws/guide/variables#exporting-a-functionvariablesResolutionMode:20210219custom:dotenvVars:${file(configs.js)}functions:hello:handler:src/hello.handlerenvironment:MY_ENV_VAR:${env:MY_ENV_VAR}
When the Serverless Framework sees${file(configs.js)}
, the variables resolver will call the function exported inconfigs.js
. The JavaScript code there includes a call todotenv.config()
, which will load all environment variables defined in.env.local
. Because this loads the environment variables into the process, plugins will also have access to them.
With afor
loop, you can load multiple dotenv files (e.g..env
and.env.local
), or withoptions.stage
, you can load files based on the value of the--stage
parameter. You can also load anydotenv
plugins you may be interested in using, such asdotenv-expand
. Because you are able to execute arbitrary JavaScript code, you are only limited by what you can do in JavaScript!
You can find a full example is available atneverendingqs/serverless-dotenv-example. Got questions or want to see more content like this? Check outneverendingqs/ask-me-anything!
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse