AWS has recently added to AWS Lambda the possibility to define variables to customize the environment the code runs in. This will enable writing code that is clean and reusable without requiring its redeployment, writes AWS Chief Evangelist Jeff Barr.
Environment variables can be used to make your function behave differently under given circumstances, without changing its implementation. A typical usage would be to adapt a function behavior to a specific lifecycle stage, e.g. development, testing, or production. Each stage could use, e.g., its own database, or different connection credentials, etc.
AWS Lambda environment variables can be defined using the AWS Console, CLI, or SDKs. This is how you would define an AWS Lambda that uses an LD_LIBRARY_PATH
environment variable using AWS CLI:
aws lambda create-function \
--region us-east-1
--function-name myTestFunction
--zip-file fileb://path/package.zip
--role role-arn
--environment Variables={LD_LIBRARY_PATH=/usr/bin/test/lib64}
--handler index.handler
--runtime nodejs4.3
--profile default
Once created, environment variables can be read using the support your language provides for accessing the environment, e.g. using process.env
for Node.js. When using Python, you would need to import the os
library, like in the following example:
...
import os
...
print("environment variable: " + os.environ['variable'])
Environment Variable are key/value pairs that are encrypted and decrypted as required. They are associated to a given version of the Lambda they belong to and can be modified freely before the Lambda is published. Once a lambda version is published, its environment variables become immutable. Rolling back to any previous version of a Lambda will also restore its environment. Any number of environment variables can be associated to a Lambda function, provided their overall size does not exceed 4 KB.