CodexBloom - Programming Q&A Platform

AWS CDK: how to to Pass Environment Variables to Lambda Function in TypeScript

๐Ÿ‘€ Views: 2 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-09
aws-cdk lambda typescript TypeScript

I'm upgrading from an older version and After trying multiple solutions online, I still can't figure this out... I've searched everywhere and can't find a clear answer. I'm currently working with an scenario with passing environment variables to my AWS Lambda function using the AWS CDK in TypeScript. I have a simple Lambda function that needs to access a database URL and an API key from the environment variables, but despite my configuration, the variables are not being set correctly. Hereโ€™s a snippet of my code where I define the Lambda function: ```typescript import * as cdk from 'aws-cdk-lib'; import * as lambda from 'aws-cdk-lib/aws-lambda'; import * as path from 'path'; export class MyStack extends cdk.Stack { constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); const myFunction = new lambda.Function(this, 'MyFunction', { runtime: lambda.Runtime.NODEJS_14_X, handler: 'index.handler', code: lambda.Code.fromAsset(path.join(__dirname, 'lambda')), environment: { DB_URL: this.node.tryGetContext('dbUrl'), API_KEY: this.node.tryGetContext('apiKey'), }, }); } } ``` In my `cdk.json`, I have set the context variables: ```json { "context": { "dbUrl": "https://mydatabase.example.com", "apiKey": "secret-api-key" } } ``` However, when I deploy the stack and invoke the Lambda function, it seems to not recognize these environment variables. Iโ€™ve checked the Lambda console, and under the function configuration, those variables are not listed. I have tried using `cdk deploy --context dbUrl=https://mydatabase.example.com --context apiKey=secret-api-key` to pass the context directly but still no luck. I also tried defining the environment variables directly in the Lambda function without using context, but that didnโ€™t work either. Could anyone suggest what I might be missing or doing wrong? I want to ensure that my Lambda function can access these environment variables correctly during execution. What am I doing wrong? My development environment is Windows. Am I missing something obvious? This is happening in both development and production on CentOS. Is this even possible?