2022-06-06 10:00:00+00:00

In distributed microservice platforms, different services often share or partition access to the same relational database. When you release updates that change database schemas, executing these migrations manually leads to deployment bottlenecks. Enforcing migrations automatically inside your Continuous Integration and Continuous Deployment (CI/CD) pipeline ensures schemas are kept in sync safely before code changes are routed production traffic.

By integrating Alembic with GitLab runner pipelines, we can automate database migrations on code pushes.


1. Running Alembic in the CD Pipeline

We configure our CD build step to apply database changes automatically when changes are pushed to main:

# migration-ci-job.yml
deploy_schema_migrations:
  stage: deploy
  image: python:3.9-slim
  script:
    - pip install alembic psycopg2-binary
    # Run database migration upgrade to head
    - alembic upgrade head
  only:
    - main
  variables:
    # Database connection URL loaded securely from vault
    DATABASE_URL: "postgresql://db_user:secret@db-prod-host:5432/main_db"

2. Enforcing Transactional Migrations

Alembic migrations are wrapped inside transactions: if a step fails midway due to a connection error, all changes are automatically rolled back, protecting database consistency.