CodexBloom - Programming Q&A Platform

AWS CDK: Lambda Function Environment Variables Not Resolving in Deployment Stage

πŸ‘€ Views: 2 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-05
aws lambda cdk typescript TypeScript

I'm upgrading from an older version and I can't seem to get I've been banging my head against this for hours... I'm working through a tutorial and I've been struggling with this for a few days now and could really use some help. I'm using the AWS Cloud Development Kit (CDK) in version 2.0 to deploy a Lambda function, and I've encountered a frustrating issue where the environment variables I set in the stack are not resolving correctly in the deployment stage. I have the following code in my stack that defines the Lambda function: ```typescript import * as cdk from 'aws-cdk-lib'; import * as lambda from 'aws-cdk-lib/aws-lambda'; import * as constructs from 'constructs'; export class MyStack extends cdk.Stack { constructor(scope: constructs.Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); const myFunction = new lambda.Function(this, 'MyFunction', { runtime: lambda.Runtime.NODEJS_14_X, code: lambda.Code.fromAsset('lambda'), handler: 'index.handler', environment: { MY_ENV_VAR: 'Hello, World!', ANOTHER_VAR: process.env.ANOTHER_VAR || 'Default_Value', }, }); } } ``` Despite having set `MY_ENV_VAR` and attempting to use `process.env.ANOTHER_VAR`, when I deploy the stack, the environment variables in the Lambda function remain undefined. I tried running the `cdk synth` command to see the generated CloudFormation template, and I can confirm that the environment variables are present in the definition of the Lambda function: ```yaml Resources: MyFunction: Type: AWS::Lambda::Function Properties: Environment: ANOTHER_VAR: Default_Value MY_ENV_VAR: Hello, World! ``` I also verified that the Lambda function's execution role has the necessary permissions to access these environment variables. After deploying, I tried invoking the function and logging the environment variables with `console.log(process.env)` to debug, but I still get undefined for both variables. I've double-checked the deployment stage and the Lambda console, and the configuration doesn’t reflect the expected values. Is there something I'm missing, or is there a known issue with CDK version 2.0 that could be causing this? Any help would be greatly appreciated! My development environment is Linux. What am I doing wrong? I'm using Typescript LTS in this project. What's the correct way to implement this? Thanks for taking the time to read this!