如何将构造添加到现有堆栈

How to add constructs to an existing stack

我正在开发一个 CDK 应用程序,它有一个 API 来接受调用者提供的堆栈引用,然后我需要向堆栈添加更多构造并 return 向调用者添加堆栈。有办法吗?

Typescript 代码示例:

static createResources(stackRef: Stack, someConfig: String): Stack {

    // Code to add more constructs to the stack based on the config parameter

    return stackRef;
}

是的,这在技术上很容易。在添加到 createResources:

的构造函数中将 stackRef 作为 scope 参数传递
new s3.Bucket(stackRef, 'MyBucket', {});

不过请记住,CDK warns against this pattern:

Technically, it's possible to pass some scope other than this when instantiating a construct, which allows you to add constructs anywhere in the tree, or even in another stack in the same app. For example, you could write a mixin-style function that adds constructs to a scope passed in as an argument. The practical difficulty here is that you can't easily ensure that the IDs you choose for your constructs are unique within someone else's scope. The practice also makes your code more difficult to understand, maintain, and reuse. It is virtually always better to find a way to express your intent without resorting to abusing the scope argument.

换句话说,CDK 模式是在 Stack 的构造函数中将子构造添加到 Stack。