Search code examples
typescriptyamlaws-cloudformationaws-cdk

Deploy failing after cdk migrate due to "Resources already exist in a stack and cannot be imported"


I've recently used the AWS IaC generator to import existing AWS resources into a CFN Stack. I'm currently trying to use 'cdk migrate' in order to be able to use CDK to manage my already existing stack.

I've successfully generated a cdk project, bootstrapped my account, and when I run 'cdk diff' I get output indicating that not much should be changing. However, it does mention that it "Could not create a change set, will base the diff on template differences (run again with -v to see the reason)"

When I run 'cdk deploy' (or run 'cdk diff -v') I receive the following error output:

MyStackName failed: Error [ValidationError]: Resources [SomeMemoryDbParameterGroup, (...)] passed in ResourceToImport are already in a stack and cannot be imported.

My current suspicion is that this is related in some manner to the naming of the resources. To continue with the example resource above, I see the following in my cdk code:

const memDbParamGroup = new memorydb.CfnParameterGroup(this, 'SomeMemoryDbParameterGroup', {
      parameterGroupName: 'pgName',
      family: 'family',
      description: 'Description goes here',
    });
    memDbParamGroup.cfnOptions.deletionPolicy = cdk.CfnDeletionPolicy.RETAIN;
    memDbParamGroup.cfnOptions.updateReplacePolicy = cdk.CfnDeletionPolicy.RETAIN;

And I see the following in the generated template file in the 'cdk.out' directory:

"SomeMemoryDbParameterGroup": {
   "Type": "AWS::MemoryDB::ParameterGroup",
   "Properties": {
    "Description": "Description goes here",
    "Family": "family",
    "ParameterGroupName": "pgName"
   },
   "UpdateReplacePolicy": "Retain",
   "DeletionPolicy": "Retain",
   "Metadata": {
    "aws:cdk:path": "MyStackName/SomeMemoryDbParameterGroup"
   }
  }

And the following in the template for my existing stack:

  SomeMemoryDbParameterGroup:
    Type: "AWS::MemoryDB::ParameterGroup"
    Properties:
      Description: "Description goes here"
      Family: "family"
      ParameterGroupName: "pgName"
    UpdateReplacePolicy: "Retain"
    DeletionPolicy: "Retain"

My hope is to be able to deploy my cdk code and manage these resources in cdk in the future WITHOUT deleting and recreating them. I found some solutions that seem like they would get the deploy to work, but they all seem to involve deleting and recreating the resources (and thus losing state data).


Solution

  • Update for anyone who finds this later: I had originally migrated by using --from-path after downloading the template file for my existing stack. It seemed to have the correct stack name, but for some reason appears to be attempting to create a new stack still.

    I resolved the issue by going back and re-migrating with --from-stack instead which worked perfectly.