简体   繁体   English

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

[英]How to add constructs to an existing stack

I'm working on a CDK app which has an API to accept caller provided stack reference, then I need to add more constructs to the stack and return the stack to the caller.我正在开发一个 CDK 应用程序,它有一个 API 来接受调用者提供的堆栈引用,然后我需要向堆栈添加更多构造并将堆栈返回给调用者。 Is there a way to do that?有没有办法做到这一点?

Example Typescript code:示例打字稿代码:

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

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

    return stackRef;
}

Yes, this is technically easy.是的,这在技术上很容易。 Pass stackRef as the scope argument in the construct constructors you add to createResources :stackRef作为范围参数传递给您添加到createResources的构造构造函数:

new s3.Bucket(stackRef, 'MyBucket', {});

Keep in mind, though, that the CDK warns against this pattern :但请记住,CDK 会针对这种模式发出警告

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.从技术上讲,在实例化构造时可以传递this的其他范围,这允许您在树中的任何位置添加构造,甚至可以在同一应用程序的另一个堆栈中添加构造。 For example, you could write a mixin-style function that adds constructs to a scope passed in as an argument.例如,您可以编写一个 mixin 风格的函数,将结构添加到作为参数传入的作用域中。 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.这里的实际困难在于,您无法轻松确保为构造选择的 ID 在其他人的范围内是唯一的。 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.找到一种表达您的意图的方法实际上总是更好,而无需滥用范围参数。

In other words, the CDK pattern is to add child constructs to a Stack in the Stack's constructor.换句话说,CDK 模式是在 Stack 的构造函数中将子构造添加到 Stack。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM