Search code examples
typescriptamazon-web-servicesaws-cdkaws-cdk-typescriptaws-cdk-context

How to set context to fix AWS CDK setContext error when updating past v1.9.0?


I’m trying to update some AWS CDK code past version 1.9.0 to version 1.152.0. However, there’s one issue that is causing a problem - the setContext code is not valid anymore.


The error message I'm seeing is ‘Cannot set context after children have been added: Tree’

The code I am trying to update is:

const app = new cdk.App();

let stage: string = app.node.tryGetContext('stage');

// AppConfig is a custom defined interface  
// stageConfig is a variable of custom defined interface, StageConfig
const appConfig: AppConfig = {
  domainName: app.node.tryGetContext('domainName'),
  isProduction: stage === 'prod',
  stageName: stage,
  // default to getting dev config if stage is other than prod or test
  stageConfig: app.node.tryGetContext(stage === 'prod' || stage === 'test' ? stage : 'dev')
};

// set appConfig as a context variable for downstream stacks to use
app.node.setContext('config', appConfig);

I believe the main issue is that when the variable app is being defined, it now needs to include the set context data. That means I cannot use app.node.tryGetContext anymore because it's referencing the variable I am trying to define.

I tried to set stage to process.env.STAGE and domainName to process.env.DOMAINNAME but both seem to always return 'undefined':

let stage = process.env.STAGE || 'dev';

let app = new cdk.App({
  context: { ['config']: {
    domainName: process.env.DOMAINNAME,
    isProduction: stage === 'prod',
    stageName: stage,
    stageConfig: process.env.STAGE === (stage === 'prod' || stage === 'test' ? stage : 'dev')
  }}
});

Solution

  • Setting context on the App level is not possible after 1.9.0 per https://github.com/aws/aws-cdk/issues/4359

    Your options are to either set it at a construct level (instead of app) or initialize the app with the context like you're doing in your second example, but then you cannot refer to any existing context variables.

    process.env contains your environment variables. If it returns undefined, that means that there's no env variable with that name.