Attempting to upgrade AWS CDK code from version 1.9.0 to version 1.152.0, I encountered a problem with the setContext code no longer being valid.
The error message states ‘Cannot set context after children have been added: Tree’
The original code that needs updating is:
const app = new cdk.App();
let stage: string = app.node.tryGetContext('stage');
// AppConfig interface
// stageConfig 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);
The issue seems to be that when defining the app
variable, it now requires including the set context data. Thus, app.node.tryGetContext
cannot be used because it references the variable being defined.
My attempts to set stage
to process.env.STAGE
and domainName
to process.env.DOMAINNAME
always result in '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')
}}
});