欢迎使用 AWS CDK。
享受车程。 ;)
实际上,帐户本身没有语义(在您的情况下是阶段)。
这与 CDK 或 Cloud Formation 无关。
您需要注意这一点。
您是对的,您可以在cdk.json 中使用CDK 上下文。
除了 CDK 内部使用的一些变量外,上下文中没有模式强制执行。
您可以在其中定义 dev 和 prod 对象。
defining the context还有其他方式。
这是一个示例,它可能是什么样子:
{
"app": "node app",
// usually there's some internal definition for your CDK project
"context": {
"dev": {
"accountId" : "prod_account",
"accountRegion" : "us-east-1",
"name": "dev",
"resourceConfig":
{
// here you could differentiate the config per AWS resource-type
// e.g. dev has lower hardware specs
}
},
"prod": {
"accountId" : "prod_account",
"accountRegion" : "us-east-1",
"name": "prod",
"resourceConfig":
{
// here you could differentiate the config per AWS resource-type
// prod has higher hardware specs or more cluster nodes
}
}
}
}
定义好之后,您需要使用-c 标志运行您的CDK 应用程序,以指定您想要拥有的配置对象(dev 或prod)。
例如,您可以使用cdk synth -c stage=prod 运行它。
这会在您的上下文中设置 stage 变量并使其可用。
成功后,您可以再次重新访问上下文并获取相应的配置对象。
const app = new cdk.App();
const stage = app.node.tryGetContext('stage');
// the following step is only needed, if you have a different config per account
const stageConfig = app.node.tryGetContext(stage );
// ... do some validation and pass the config to the stacks as constructor argument
正如我所说,上下文是执行此操作的一种方式。
但是,它也有缺点。
它是 JSON,没有代码。
我更喜欢为每个资源配置(例如 S3)设置 TypeScript 类型,并将它们作为一个普通对象连接在一起。
该对象映射账户/区域信息和对应的资源配置。