Skip to content

Instantly share code, notes, and snippets.

@davidwtbuxton
Created November 7, 2024 15:23
Show Gist options
  • Save davidwtbuxton/ea3cdddd280fff5deac03d9702801e00 to your computer and use it in GitHub Desktop.
Save davidwtbuxton/ea3cdddd280fff5deac03d9702801e00 to your computer and use it in GitHub Desktop.
Google Cloud Build steps to run Django database migrations against Cloud SQL
steps:
- id: build-temp-image
name: gcr.io/cloud-builders/docker
script: |
#!/usr/bin/env bash
set -o errexit -o nounset -o pipefail
# A custom image with Python + cloud-sql-proxy. We can then use this for
# connecting to the database when running django commands.
docker build -t $_TEMP_IMAGE_NAME - <<EOF
FROM python:3.12-slim
COPY --from=gcr.io/cloud-sql-connectors/cloud-sql-proxy /cloud-sql-proxy /usr/local/bin/cloud-sql-proxy
EOF
- id: install-python-deps
name: $_TEMP_IMAGE_NAME
script: |
#!/usr/bin/env bash
set -o errexit -o nounset -o pipefail -o xtrace
python -m pip install --quiet --upgrade pip
python -m pip install \
--quiet --user --no-warn-script-location --requirement requirements.txt
- id: apply-migrations
name: $_TEMP_IMAGE_NAME
script: |
#!/usr/bin/env bash
set -o errexit -o nounset -o pipefail -o xtrace
# Run the SQL proxy in the background.
cloud-sql-proxy --port 5432 "${_SQL_INSTANCE}" &
sleep 2
python manage.py collectstatic --no-input
python manage.py migrate --plan --no-input
python manage.py migrate --no-input
substitutions:
_TEMP_IMAGE_NAME: "build-temp"
# Note the hard-coded region, which happens to be correct for this project.
_SQL_INSTANCE: "${PROJECT_ID}:us-central1:${PROJECT_ID}"
options:
automap_substitutions: true
dynamic_substitutions: true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment