How to test if CDK context key exists?

Viewed 1217

I have a use case for storing some key-value in the cdk.context.json, however if cdk.context.json doesn't exist or if it doesn't contain the key I want CDK to fall back to other code to discover the values.

For example, pretend that the key is "availability-zones". I want to store the value in cdk.context.json, like so:

{
  "availability-zones:account=123456789012:region=us-west-2": [
    "us-west-2a",
    "us-west-2b",
    "us-west-2c",
    "us-west-2d"
  ]
}

But if it isn't stored there, I want my CDK to use a third-party library to find the values. One way I can do this is to test if the context has the availability-zones key, and retrieve the values if specified. How can I do this with CDK?

1 Answers

There is actually an environment variable from which this information should be able to be derived. For example, when using Node.js:

const context = JSON.parse(process.env.CDK_CONTEXT_JSON)

if(context.['availability-zones:account=123456789012:region=us-west-2']) {
   // do something
}

Hope that helps!

Related