Making RDS Database Versioning & Instrumentation Easy with Liquibase & CloudFormation
Reposted with permission from Martin Whittington, Head of Platform @oddschecker.
Database schema changes are risky – learn how Liquibase can help make these changes in a controlled and stepped manner.
Database schema changes need to be managed carefully. Rolling out updates without fully understanding the ramifications can be catastrophic especially if, for example, a table has been nominated for “the drop”.
The team over at Liquibase has provided a wonderful database versioning tool that can be used to help make these sorts of changes in a controlled and stepped manner.
Let's say we have three tables; Orders, Products, and Sales Reps. An order can contain one or more products. An order is also usually linked to a single sales rep so that the commission can be calculated correctly. Now, let's imagine that a decision has come down from the top that commission is no longer being paid and the database needs updating to reflect this. The change would be removing the link from the orders table to the sales rep table and then eventually removing the sales rep table altogether. Each change would be a version-controlled update using changelogs:
Our master changelog contains all the files to include (run in order top to bottom). Let's assume that db.changelog-1.0.xml was used to create the initial DB schema. We now want to add a new changelog that will:
Drop the FK constraint between the order and sales_rep table.
Drop the sales_rep_id column from the order table.
Drop the sales_rep table.
Now we need to add this to our master log to roll out the update:
Once this is tested on a local non-critical DB, we can package this as part of our AWS Lambda Jar. The Lambda code looks like this:
public class RDSManager implements RequestHandler
In logical order, the Lambda does the following:
Checks the request type. If it is a ‘Delete’ request, we just return a success to CloudFormation.
Next, the code fetches AWS SSM Parameters to securely connect to the RDS instance.
Once the parameters have been fetched, a connection to the RDS instance is made.
Once the connection is established, Liquibase runs the changelog file to update the database schema.
Once Liquibase has completed, a success signal is sent back to CloudFormation
The connection is closed.
I’ll let you all figure out the CloudFormation code to run this, that’s the easy part!