4
votes

I am building application with cloudformation template and now migrating to using CDK. But when I run cdk deploy command, it always complains about resources already exist even I use the same stack name. Is there a way run CDK without tear down any cloudformation stack?

I know there is import resources feature but my case is that the resources will belong to the stack managed by CDK. If I use import, that means the resources exist outside of the stack. How can I make it work automatically? The logic should be import the resource if it exists, otherwise create it.

2

2 Answers

6
votes

Unfortunately there will be some manual steps, however with a bit of work, most of these steps can be scripted. Here's roughly how I've done CF to CDK stack migrations in the past:

  1. For all the resources you are wanting to migrate out of your old CF stack, set a DeletionPolicy of Retain.
  2. Do a CloudFormation stack update with these changes - this will 'detach' these resources from your stack when you delete the stack in the next step, so that they can be imported to your CDK stack.
  3. Delete the CloudFormation stack. The resources in the stack should continue to exist.
  4. Redefine the resources you are preparing to import in your CDK stack. Try to mirror your existing resources as closely as possible, this will help you consolidate any drifts after importing.
  5. Import these detached resources to your CDK stack via a ChangeSet. You can do so either via the AWS Console directly, or via CLI (e.g. aws cloudformation create-change-set --change-set-type IMPORT --resources-to-import ...)
  6. Run drift detection on your CDK CF stack. Fix any drifts. Ideally there would be none if you've modeled the resources correctly in CDK, however there may be small differences due to defaults set by CDK.
0
votes

You have to import existing resources to CDK. Further info about this as well as examples of this operation are provided in AWS docs for CDK:

You can turn the resource's ARN (or another identifying attribute, or group of attributes) into an AWS CDK object in the current stack by calling a static factory method on the resource's class.