Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A javascript module that demonstrates decrypting some KMS-encrypted environment variables
const AWS = require('aws-sdk');
const encryptedEnvironmentVariableNames = ['SOME_VARIABLE', 'SOME_OTHER_VARIABLE'];
// This module exports a function that returns a promise for obtaining
// a decrypted copy of the environnment.
// Configure it by putting the name of each environment variable you would like to
// decrypt above.
// When successful, the promise resolves to a copy of process.env with
// each variable listed above decrypted.
const kms = new AWS.KMS();
// This function is the core decryption.
// It's just a promisified kms.decrypt call
const decrypt = data =>
new Promise((resolve, reject) =>
CiphertextBlob: Buffer.from(data, 'base64')
(err, result) => {
if (err) {
} else {
const decryptedEnv = Promise.all(
// This uses the named variables defined at the top to determine what to decrypt.
// Depending on your needs, you could instead filter the existing environment
// on some pattern (eg all env vars starting with "ENCRYPTED_SECRET_") to
// determine what to decrypt. =>
decrypt(process.env[name]).then(data => ({ [name]: data }))
).then(array =>
array.reduce((config, item) => ({ ...config, ...item }), { ...process.env })
// We export a promise directly, so that it will stay resolved in
// future executions of the same lambda, reducing the number of decryption calls
module.exports = decryptedEnv;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.