Decrypting AWS lambda environment variables using node 4.3 and KMS

AWS recently announced support for environment variables, and KMS integration to encrypt and decrypt them. Here’s how to do it using the AWS console UI.

Create a KMS key

  • At the top right of the console UI, find go to My Security Credentials
  • At the bottom left, find the KMS section for Encryption keys

Screen Shot 2016-12-25 at 10.18.11 PM.png

  • Create a new key, make sure that in “Define key Usage Permissions”, the role associated has permission to decrypt using KMS.Screen Shot 2016-12-25 at 10.10.42 PM.png

Create lambda function and encrypt an environment variable

  • Select the “Hello World” blueprint

Screen Shot 2016-12-25 at 10.23.07 PM.png

  • Create a new lambda function. In the code section, use the following:
console.log('Loading function');
var AWS = require('aws-sdk');
var kms = new AWS.KMS();
var encrypted = process.env['foo'];

exports.handler = (event, context, callback) => {
    kms.decrypt({CiphertextBlob: new Buffer(encrypted, 'base64')}, (err, data) => {
        if (err) {
            console.log('Decrypt error:', err);
            return callback(err);
        var decrypted = data.Plaintext.toString('ascii');
        callback(null, decrypted);

  • In the other settings, check the “Enable encryption helpers” box and select the KMS key you have created
  • In the environment variables, add “foo” as a key, and anything as the value
  • Click “encrypt”, you should see the value turn into a bunch of dots
  • In the role section, make sure you select your role which has KMS:decrypt permissions, otherwise your lambda will error out

Screen Shot 2016-12-25 at 10.26.13 PM.png

Once you hit “encrypt”

Screen Shot 2016-12-25 at 10.27.03 PM.png

Test your function

Finally, save and test your function, you should see the unencrypted value echoed out like so:

Screen Shot 2016-12-25 at 10.41.06 PM.png