Use dotenvx with AWS Lambda

Use dotenvx with AWS Lambda

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.

aws.amazon.com

On the next page, choose Upload from .zip File. And upload the function.zip you created earlier.

aws.amazon.com

Click Test and you will see Hello encrypted:1234 in the body response.

aws.amazon.com

Set DOTENV_PRIVATE_KEY

Lastly, set the DOTENV_PRIVATE_KEY to decrypt your value at runtime. Click Add environment variables.

aws.amazon.com

Set DOTENV_PRIVATE_KEY and its value from your .env.keys file.

aws.amazon.com

After saving that, click Test and this time you will see Hello World in the body response.

aws.amazon.com

That's it! Distributing your lambdas is now much safer - as they only contain encrypted values.