How to pass Environment Variables to Lambda in AWS CDK


Borislav Hadzhiev

Fri Apr 23 20212 min read


Photo by Mike Giles

Updated on Fri Apr 23 2021

Passing Environment Variables to Lambda Functions in CDK #

In order to pass environment variables to our Lambda function we have to set the environment property, when instantiating the function construct.

The code for this article is available on GitHub
const myFunction = new NodejsFunction(this, id, { // setting environment variables ๐Ÿ‘‡ environment: { region: cdk.Stack.of(this).region, availabilityZones: JSON.stringify(cdk.Stack.of(this).availabilityZones), myEnvVariable: 'some value', }, runtime: lambda.Runtime.NODEJS_14_X, memorySize: 1024, timeout: cdk.Duration.seconds(5), handler: 'main', entry: path.join(__dirname, `/../src/my-function/index.js`), });

The environment object is a map of key value pairs of type string. This means that we have to call JSON.stringify on any non-string value that we want to pass to the lambda function, in our case the array of availability zones.

In our lambda function code we can then access the environment variables by using the process.env object.

async function main(event) { // accessing environment variables ๐Ÿ‘‡ console.log('region ๐Ÿ‘‰', process.env.region) console.log('availabilityZones ๐Ÿ‘‰', process.env.availabilityZones) console.log('myEnvVariable ๐Ÿ‘‰', process.env.myEnvVariable) return {body: JSON.stringify({message: 'SUCCESS'}), statusCode: 200}; } module.exports = {main};

The result of the function invocation looks like:

lambda invocation

We can also verify that the environment variables have been set by opening the Lambda AWS console and clicking on Configuration:

environment variables console

Summary #

In order to pass environment variables to a Lambda function we have to set the environment property on the function construct to a map of key value pairs of type string.

We are then able to access the environment variables on the process.env object in our lambda function.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee