Search code examples
amazon-web-servicesamazon-rdsaws-cdkamazon-aurora

Amazon RDS restore & aws-cdk infrastructure as a code sync


I'm fairly new to AWS CDK through code and I've been looking around how to restore a database. I understand that you cannot restore Aurora database into an existing instance from snapshot (1) (2). My issue lies in the fact that we use infrastructure as a code, and therefore I need to sync the "new" database into the "old" IaC (e.g. number of instances is different)

I have managed to create a new database and change all the configurations required. However, one point I'm missing is aligning this with aws-cdk. Specifically:

  • I create a new database cluster from and old snapshot
  • I change the connections of my application to use this new database cluster
  • I sync my IaC with the AWS state

The last point is the one that is eluding me. How do I set up my code using aws-cdk so that I use the restored database (setup, migrations, instances, ...) rather than the old one?

I've also tried to change the name to the restored one. However, I then encounter issues when I deploy to different environments - they create a new database rather than work with the existing one already.


Solution

  • In your CDK app, remove the existing cluster resource and add a new one. The "adding" step can be done on a snapshot or an existing cluster.

    From a snapshot

    CDK and CloudFormation can create a new cluster from a snapshot. The relevant CDK construct is DatabaseClusterFromSnapshot.

    The steps would be:

    1. Remove the existing cluster construct from the stack. Pay attention to the cluster's removal policy, which governs what happens to a removed resource. Deploy the changed app to remove the "old" cluster from CDK management.
    2. Create a new cluster from a snapshot. Pass a snapshot identifier (name or ARN) as a prop to DatabaseClusterFromSnapshot.

    From an existing cluster

    Alternatively, you can import an existing cluster into a CDK stack with the cdk import CLI command. CDK import uses CloudFormation import functionality under the hood. AWS::RDS::DBCluster is a resource type that supports import.

    Once you have imported the cluster, it will be part of your CDK stack.

    The steps would be:

    1. Step 1 as above
    2. Import the cluster by adding new cluster construct, following the step-by-step instructions for cdk import. Note the doc's warning Do not add any other changes! You must also make sure to exactly model the state that the resource currently has.