How to run database migrations within a CDK Pipeline

Viewed 441

Is there a good pattern for running database migrations within a CDK Pipeline?

Normally (without a CDK Pipeline) I would achieve this with a deploy script that:

  • deploys the database stack
  • waits for the database stack to complete
  • runs the db migrations
  • deploys the API stack

Is there any way to do this in a CDK Pipeline app (run migrations after the Database stack is deployed but before the API stack is)?

export class MyStage extends Stage {  
  constructor(scope: Construct, id: string, props?: StageProps) {
    super(scope, id, props);
    const dbStack = new DatabaseStack(this, 'Database');
    const apiStack = new ApiStack(this, 'Api', {
        dbUrl: dbStack.dbUrl
    });    
  }
}
1 Answers

Things like this I would put in a CustomResource: https://docs.aws.amazon.com/cdk/api/latest/docs/custom-resources-readme.html

Basically you write a lambda that will handle CREATE event and takes the database as a Property. Then it would have the code that would normally be your migration script. You can just ignore the update/delete events or maybe do some data backup on delete. Just remember that the events are for the custom resource, not necessarily the database (even though they may coincide).

Related