How to Use Encrypted Environment Variables in Lambda Functions

Need to write a Lambda function that will log in to something? Don’t hard-code your username or password in the script – store them as encrypted environment variables instead! Here’s how:

First, you’ll need to create a KMS key that your account will use to encrypt the variables.

In the AWS console, head over to IAM, and then click on “Encryption keys” at the bottom-left, and create a key with a name you can remember. Then go to the Lambda service, and click on your Lambda function. If you scroll down a little you should see a “Environment Variables” section on the left side.

Add two variables: one called “username” and another called “password.”

Just below this, click the triangle to expand the “Encryption configuration” section and check the box, and then enter the key name that you just created into the two fields below it to encrypt in transit and at rest. Once you do that you can click the “Encrypt” button next to each field you want encrypted, and once you click the “Save” button at the top, you’re done!

Now that you’ve created the variables in your function and encrypted them, you can reference them from your code. If you’re using Python 3.6, the relevant lines to add at the top are:

import os
from base64 import b64decode

ENCRYPTEDusername = os.environ['username'] 
DECRYPTEDusername = boto3.client('kms').decrypt(CiphertextBlob=b64decode(ENCRYPTEDusername))['Plaintext'] 
ENCRYPTEDpassword = os.environ['password'] 
DECRYPTEDpassword = boto3.client('kms').decrypt(CiphertextBlob=b64decode(ENCRYPTEDpassword))['Plaintext']

You only want to decrypt these variables once, so put them above the Lambda handler, which is a line that looks like this:

def lambda_handler(event, context):

You can now use these variables like any other variables within your script. For instance, you may want to assign the decrypted variables new names:

user = DECRYPTEDusername
passwd = DECRYPTEDpassword

Now, when Security asks you to change your passwords, you won’t have to hunt through your code to do it – you can just make the change in the Lambda function’s properties and move on with your life, content in the knowledge that it’s a bit more secure. :)

The only drawback to encrypting your variables this way is you can’t deploy encrypted environment variables via a CloudFormation script. To do that you may want to look into using something like the AWS Parameter Store.