CB_at_Sw
CB_at_Sw

Reputation: 387

AWS CDK: How to pass CDK context variable to C# Lambda startup code

I have a .NET Lambda function written in C#, implemented as a .NET Mimimal API with (as described here). I am using the CDK (TypeScript) to define the AWS resources.

The build pipeline includes shell scripting to pass in a parameter to define the stage (i.e., dev vs. qa vs. beta vs. prod) as follows:

cdk synth -c "stage=${StageName}"

In my CDK code, I read this variable as follows:

const stage = this.node.tryGetContext('stage');

This is used to then determine which environment-specific settings to use in cdk.json when defining the stack (endpoints, etc.).

My question is: is there a way to pass this variable into the Lambda function's startup logic? I know that I can pass it into the body of the Lambda function itself as a parameter. But I really need to be able to pass it into the app startup logic that gets executed before the function body is entered (i.e. when I'm telling the configuration logic which appsettings.{env}.json to use).

Is this possible via the CDK?

Upvotes: 0

Views: 300

Answers (1)

CB_at_Sw
CB_at_Sw

Reputation: 387

I think I found the answer.

I was able to get it to work by setting the .NET environment variable in lambda.FunctionProps's environment field, i.e.:

environment: {
    'stage': stage
}

...which can then be read in a .NET app just like any other environment variable, i.e.: var stage = Environment.GetEnvironmentVariable("stage");

I had no idea that the CDK could set .NET environment variables in such a way!

Upvotes: 0

Related Questions