Decrypting multiple env. variables in AWS Lambda
You can use promises to achieve this. See the example below for decrypting both a username and password via KMS. You can add as many additional decryption promises to the decryptPromises
array as you'd like:
const AWS = require('aws-sdk'); const encrypted = { username: process.env.username, password: process.env.password }; let decrypted = {}; function processEvent(event, context, callback) { //do work } exports.handler = (event, context, callback) => { if ( decrypted.username && decrypted.password ) { processEvent(event, context, callback); } else { const kms = new AWS.KMS(); const decryptPromises = [ kms.decrypt( { CiphertextBlob: new Buffer(encrypted.username, 'base64') } ).promise(), kms.decrypt( { CiphertextBlob: new Buffer(encrypted.password, 'base64') } ).promise() ]; Promise.all( decryptPromises ).then( data => { decrypted.username = data[0].Plaintext.toString('ascii'); decrypted.password = data[1].Plaintext.toString('ascii'); processEvent(event, context, callback); }).catch( err => { console.log('Decrypt error:', err); return callback(err); }); } };
You can find more information on how promises have been implimented for the AWS SDK in the Support for Promises in the SDK documentation.