Reputation: 45
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. 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;
}
Upvotes: 0
Views: 909
Reputation: 25739
Yes, this is technically easy. Pass stackRef
as the scope argument in the construct constructors you add to createResources
:
new s3.Bucket(stackRef, 'MyBucket', {});
Keep in mind, though, that the 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.
In other words, the CDK pattern is to add child constructs to a Stack in the Stack's constructor.
Upvotes: 3