Use dotenvx with AWS Lambda
Use dotenvx with AWS Lambda
Find code examples for this guide on GitHub.
Initial setup
Create the lambda handler in the language of your choice.
// index.js
exports.handler = async (event) => {
return {
statusCode: 200,
body: 'Hello World'
}
}
Add dotenvx
Install dotenvx into the lambda.
$ npm install @dotenvx/dotenvx --save
Add it to your lambda handler and place HELLO env in the body.
// index.js
require('@dotenvx/dotenvx').config()
exports.handler = async (event) => {
return {
statusCode: 200,
body: `Hello ${process.env.HELLO}`
}
}
Add .env file
Add your .env file.
# .env
HELLO="World"
And encrypt it.
$ dotenvx encrypt
Zip It Up
Zip everything up – making sure to ignore .env.keys.
zip -r function.zip . -x ".env.keys"
Upload to AWS Lambda
Create a function, select your runtime, and select x86_64.
On the next page, choose Upload from .zip File. And upload the function.zip you created earlier.
Click Test and you will see Hello encrypted:1234 in the body response.
Set DOTENV_PRIVATE_KEY
Lastly, set the DOTENV_PRIVATE_KEY to decrypt your value at runtime. Click Add environment variables.
Set DOTENV_PRIVATE_KEY and its value from your .env.keys file.
After saving that, click Test and this time you will see Hello World in the body response.
You succesfully add encryption to your .env files. This is safer than scattering your secrets across third-party platforms and tools. When you need to update a secret, run dotenvx set KEY value and redeploy.
That's it! Distributing your lambdas is now much safer - as they only contain encrypted values.