Lambda Function - Encrypt Environment Variables

Lambda functions supports environment variables and sometimes sensitive information like database password can be stored in the environment variables. To secure the settings, the environment variables can be encrypted.

Lambda functions feature makes it very easy to encrypt the variable. Simply click on the "Enable encryption helpers" option near the environment variables settings.

Once clicked, a new screen will appear where the encryption key needs to be selected. If no encryption keys are available, then an encryption key needs to be created from the AWS KMS service. Once a key is selected, the "Encrypt" button becomes availble next to the environment variable.

When the Encrypt button is clicked, the environment variable is encrypted and no longed can be seen. It can be seen by using the Decrypt button though.

The console also provides option to download and use the code for using the encrypted key. This is useful as the code does not need to be written. The sample code from AWS is below.

const AWS = require('aws-sdk');

const encrypted = process.env['api_url'];
let decrypted;

function processEvent(event, context, callback) {
    // TODO handle the event here

exports.handler = (event, context, callback) => {
    if (decrypted) {
        processEvent(event, context, callback);
    } else {
        // Decrypt code should run once and variables stored outside of the function
        // handler so that these are decrypted once per container
        const kms = new AWS.KMS();
        kms.decrypt({ CiphertextBlob: new Buffer(encrypted, 'base64') }, (err, data) => {
            if (err) {
                console.log('Decrypt error:', err);
                return callback(err);
            decrypted = data.Plaintext.toString('ascii');
            processEvent(event, context, callback);