Search code examples
typescriptaws-cloudformationrefactoringaws-cdk

How can I do refactoring of CDK code using TypeScript?


I have created a CDK stack and put all my code inside (S3 bucket, Lambda etc.); the code is also in production, so I am not able to delete anything or lose any data and logs.

I want to refactor that stack in a way to create some kind of class that is separated from that stack where I'll put all those resources, and then call it inside of my stack.

I tried to do this but every time CloudFormation tries to create new resources. Is there any better way to do this, without losing anything?

ERROR that I get is related to "resources already exist".


Solution

  • The issue is the fact that when a resource's logical ID changes, the resource is recreated. When you extract your resources into a separate construct, you'll change the logical IDs of all its resources.

    There is a built-in partial solution to this explained in the documentation for the Stack.allocateLogicalId method:

    If a component is named "Default" it will be omitted from the path. This allows refactoring higher level abstractions around constructs without affecting the IDs of already deployed resources.

    So if you instantiate your construct in your stack with the ID Default, the logical IDs of all your resources will stay the same.

    An obvious limitation of this is that you can only have a single construct with the name Default in the same scope.

    Another solution would be to extract them into a plain TypeScript class that's not a Construct, and simply pass the stack's scope to all the resources instead of passing this in the class.