Hi! Is there any way I can make Pulumi automatical...
# typescript
b
Hi! Is there any way I can make Pulumi automatically detect that resources have a
parent
when I make them fields/properties of a ComponentResource class? E.g. here, I would really like to not have to explicitly specify `{ parent: this }`:
Copy code
class A extends pulumi.ComponentResource {
  readonly id: random.RandomId;

  constructor(name: string, args: {}, opts: pulumi.ComponentResourceOptions) {
    super('martin:A', name, {}, opts);
    this.id = new random.RandomId(
      name,
      { byteLength: 42 },
      { parent: this }
    );
  }
}
I think that setting a Pulumi resource as a field in a class that extends pulumi.ComponentResource like I do in the example (and in pretty much all of my code) is a pretty clear expression of intent for the resource to be a child of the component resource class. I do it this way so I can set
providers: [k8sProvider, gcpProvider]
and
protect: true
on a single parent resource instead of passing the correct provider to every single resource. And the logical grouping in the diff output is nice too, but not enough that I’d bother to set a field on Every Single Resource. This is a source of continuous frustration as I keep forgetting about it when I add new resources to classes, and don’t always notice even when I run
pulumi up
given that it’s completely valid to define a resource without a parent 😅
g
It can be done, not sure if it is a great idea to do it for all `ComponentResource`s, it would be a breaking change for everyone not setting the parent. You can create a
AutoParentComponentResource
and use that as your base class.
l
I just added a lint rule that requires that every resource constructor is passed all parameters (opt is no longer optional). And our standard shape for constructing child resources is
const child = new Resource(name, args, { ...opts, parent: parent})
. The splat / spread operator is great here. I don't recommend using
parent: this
unilaterally. Lots of child resources in my stacks are children of children, so
this
would be wrong.
b
Thank you both! This makes sense. I’ll try both out and see if they work for me 🙂