Lambda Function - Environment Variables

Lambda functions feature has the option to create environment variables which are more like settings or constants that can be used by the lamda function. The environment variables can contain data like the name of a S3 bucket or a database host or a web api url, etc. The environment variables are useful to separate the application logic from the settings for the function.

In NodeJS, the environment variables can be easily accessed using process.env.

it is very easy to create the environment variables in lambda. Towards the end of the function options, there are options to create the environment variables as shown below.


In NodeJS, the environment variables can be accessed easily as shown below.



    exports.handler = (event, context, callback) => {
    //display the environment variables
    outputEnvironmentVariables();
    
    var result = add(20, 30);
    callback(null, result);
    };

    function outputEnvironmentVariables() {
        console.log('s3_bucket: ' + process.env.s3_bucket);
        console.log('api_url: ' + process.env.api_url);
    }

    function add(num1, num2) {
        return num1 + num2;
    }

The environment variables can contain sensitive information like the database password and obviously it should not be displayed and be available on screen. Thus lambda supports encrypting the environment variables if needed.

The environment variables can also contain data specific to a platform. For example, the NODE_PATH variable refers to the location where the executable for NodeJS are stored.

Environment Variables and Versioning

Lambda function feature supports versioning making it easy to store and access multiple versions of the same code. The environment variables along with memory and timeout limits are specific to the version and can only be accessed by that version. If different environment variables should have been used instead, then a different version of the code should be used. It would be easy just to create an alias of the function and change it to point to the required version.