Joey Yi Zhao
Joey Yi Zhao

Reputation: 42500

How can I migrate from cloudformation to CDK without delete existing stacks?

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.

Upvotes: 6

Views: 3296

Answers (3)

wangzishan
wangzishan

Reputation: 1

In general, you couldn't.

The CDK is techncially a wrapper of CloudFormation to help user to use CloudFormation. It helps user to generate the raw CloudFormation template in JSON. (It is very bad experience to deal with raw CloudFormation template directly) For the feature request here, it is beyond the current support by CDK, but requires underlying support from the CloudFormation.

Upvotes: -1

Matthew
Matthew

Reputation: 170

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.

Upvotes: 9

Marcin
Marcin

Reputation: 238229

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.

Upvotes: 0

Related Questions