Liquibase、Terraform 和 Spring 引导问题

Liquibase ,Terraform and Spring Boot question

我正在使用 terraform 创建 RDS 极光 mysql。我使用 SpringBoot 连接到它。我的问题是关于创建 table。 我认为 terraform 会创建 table,但看起来 SpringBoot 连接到数据库并使用 liquibase 创建 table。 这个对吗。 我希望在通过 terraform 调用 liquibase 创建数据库时创建 tables,但找不到任何详细说明如何执行此操作的文档,

Liquibase 确保通过 liquibase 进行的任何更改在下一个 运行 中也是一致的。它在 运行ning 时使用两个 tables:DATABASECHANGELOGLOCK DATABASECHANGELOG 其中 xxxLOCK 用于锁定数据库,同时 运行ning 脚本和 DATABASECHANGELOG 跟踪对数据库所做的更改。可能是 table 添加、更新列、插入数据等

因此所有这些都将在 SpringBoot 应用程序启动时 运行。您需要一些其他机制来执行您期望的操作。

不,terraform 不会为您创建数据库表。它怎么知道如何处理模式等?也许你可以 local-exec provisioner,但它看起来确实很合适。您可以创建一个提供程序来与数据库交互。我想你想要的是让 terraform 创建数据库,然后让你的应用程序管理表。

数据库表应由 liquibase 脚本创建。为确保这一点,您需要通过在应用程序配置中提供数据库连接详细信息,使用 spring 引导应用程序配置 liquibase。这意味着,在 liquibase 执行之前,必须已经创建了数据库(手动或由进程自动创建)。然后,您还可以在自动化流程或管道中触发 liquibase 执行(通过 mvn liquibase:update 或 运行 应用程序)。

带有 spring 引导的典型 liquibase 配置可能如下所示:

application.yaml:

spring:   
  datasource:
    url: jdbc:postgresql://localhost:5432/db1
    username: test
    password: test   
  liquibase:
    enabled: true
    change-log: classpath:changelog.xml

changelog.xml:

<?xml version="1.0" encoding="UTF-8"?>

<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.8.xsd">

    <include file="change-sets/create-table1.xml"/>


</databaseChangeLog>

change-sets/create-table1.xml:

<?xml version="1.0" encoding="UTF-8"?>

<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.8.xsd">

    <changeSet id="create-table1-ddl" author="bmfirat">
        <createTable tableName="table1">
            <column name="id" type="BIGINT" autoIncrement="true" >
                <constraints primaryKey="true" nullable="false" primaryKeyName="pk_table1"/>
            </column>
            <column name="title" type="varchar(255)">
                <constraints nullable="false" unique="false"/>
            </column>           
            <column name="description" type="varchar(255)">
                <constraints nullable="false" unique="false"/>
            </column>   
        </createTable>
        <rollback>
            <dropTable tableName="table1"/>
        </rollback>
    </changeSet>

</databaseChangeLog>