在 AWS CDK 中识别生产和开发环境的正确方法是什么?

What is the correct way to identify production & development environment in AWS CDK?

我正在学习 AWS 云开发工具包 (CDK)。

作为这次学习的一部分,我试图了解我应该如何正确处理生产和开发环境。

我知道 AWS CDK 提供 environment 参数以允许将堆栈部署到特定帐户。

但是,如何为开发堆栈和生产堆栈提供特定选项? AWS CDK 似乎没有默认提供它,或者我 missing/misunderstanding 什么?

一个非常简单的示例可能是我想要一个名为 my-s3-bucket-dev 的 S3 存储桶用于我的开发帐户,一个名为 my-s3-bucket-prod 的存储桶用于我的生产帐户。但是然后如何拥有例如在 AWS CDK 中正确处理的变量 stage ?

我知道我可以在 cdk.json 文件中添加参数,但同样,我不知道如何正确使用此文件来依赖部署的堆栈,即生产与开发。

感谢支持

欢迎使用 AWS CDK。 享受车程。 ;)

实际上,帐户本身没有语义(在您的情况下是阶段)。 这与 CDK 或 Cloud Formation 无关。 你需要注意这个。

你说得对,你可以在 cdk.json 中使用 CDK 上下文。 除了 CDK 内部使用的一些变量外,上下文中没有实施模式。 您可以在其中定义 devprod 对象。 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
      }
    }

  }
}

有了这个定义,您需要 运行 您的 CDK 应用程序使用 -c 标志来指定您想要的配置对象(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 类型,并将它们连接在一起作为一个普通对象。 该对象映射account/region信息和相应的资源配置。