Search code examples
aws-cdk

AWS CDK: Moving resources between stacks


Is it possible to move a DB from one Stack to another? Here is the example:

export class ParentStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const dynamodbTable = new dynamodb.TableV2(this, "Name", {
      tableName: "aName",
      partitionKey: { name: "sessionID", type: dynamodb.AttributeType.STRING },
      sortKey: { name: "timestamp", type: dynamodb.AttributeType.STRING },
    });
  }
}

But I want to move the DB down to another class to have the following result:

export class ParentStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    new ChildStack(this, "ChildStack")
  }
}

I have tried to simply move:

const dynamodbTable = new dynamodb.TableV2(this, "Name", {
  tableName: "aName",
  partitionKey: { name: "sessionID", type: dynamodb.AttributeType.STRING },
  sortKey: { name: "timestamp", type: dynamodb.AttributeType.STRING },
});

into ChildStack, but the best that I manage to get was my modification complaining that the DB already exists with this name.

The two approaches that I can see are:

  • leaving the creation of the DB in the parent and passing down its reference to the children
  • call the DB as follow dynamodb.TableV2.fromTableName(scope, id, "aName"); (if deleted from CDK)

I'm wondering if there is alternative way to get closer to what I want to do.


Solution

  • You'll need to do this manually using the AWS CLI or Console:

    • Ensure the table's RetentionPolicy is set to RETAIN so it isn't deleted after being removed from a stack.
    • Remove it from the existing stack (this may also include resolving validation errors such as dependencies)
    • Import the resource into the new stack.
    • Retry your CDK deployment

    EDIT:

    AWS Guide

    "You can manage your resources using AWS CloudFormation regardless of where they were created without having to delete and re-create them as part of a stack."

    A CDK step-by-step example with