How to pass Environment Variables to Lambda in AWS CDK

avatar

Borislav Hadzhiev

Last updated: Apr 13, 2022

banner

Photo from Unsplash

Passing Environment Variables to Lambda Functions in CDK #

In order 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 code 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 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 #

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.