How to pass Environment Variables to Lambda in AWS CDK

avatar
Borislav Hadzhiev

2 min

banner

# Passing Environment Variables to Lambda Functions in CDK

To pass environment variables to a Lambda function, we have to set the environment property, when instantiating the function construct.

The code for this article is available on GitHub
lib/cdk-starter-stack.ts
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_16_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 this case the array of availability zones.

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

src/my-function/index.js
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 as follows:

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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2023 Borislav Hadzhiev