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')
}}
});