I use the same container that is about to be deployed, it contains everything necessary to also run migrations. I used the docs in the link I sent in the original answer as a reference and simply send a POST to the right Google API containing the YML file that defines the job. For me that file looks something like this:
apiVersion: batch/v1
kind: Job
metadata:
name: {{ JOB_NAME }}
spec:
template:
spec:
containers:
- name: myapp-web-migrator
image: {{ APP_CONTAINER_TAG }}
env:
- name: DJANGO_ENVFILE_PATH
value: /secrets/django/env
command: ["/bin/bash", "-c"]
args:
- |
trap "touch /tmp/pod/task-terminated" EXIT
python manage.py migrate
volumeMounts:
- mountPath: /secrets/django
name: env
readOnly: true
- mountPath: /tmp/pod
name: tmp-pod
- name: cloudsql-proxy
command: ["/bin/sh", "-c"]
args:
- |
/cloud_sql_proxy -instances=myapp-prod:us-central1:myapp-db=tcp:5432 -credential_file=/secrets/cloudsql/credentials.json &
CHILD_PID=$!
(while true; do if [[ -f "/tmp/pod/task-terminated" ]]; then kill $CHILD_PID; echo "Killed $CHILD_PID as the main container terminated."; fi; sleep 1; done) &
wait $CHILD_PID
if [[ -f "/tmp/pod/task-terminated" ]]; then exit 0; echo "Job completed. Exiting..."; fi
imagePullPolicy: IfNotPresent
resources: {}
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
volumeMounts:
- name: cloudsql-instance-credentials
mountPath: /secrets/cloudsql
readOnly: true
- name: cloudsql
mountPath: /cloudsql
- name: tmp-pod
mountPath: /tmp/pod
readOnly: true
volumes:
- name: cloudsql-instance-credentials
secret:
defaultMode: 420
secretName: cloudsql-instance-credentials
- name: env
secret:
defaultMode: 420
secretName: {{ ENVFILE_KEY_NAME }}
- name: cloudsql
emptyDir: {}
- name: tmp-pod
emptyDir: {}
restartPolicy: Never
backoffLimit: 4
Note that this contains a "sidecar" container as is required to talk to Cloud SQL, yours may or may not need this depending on how you connect to your database. Note also that this is a template, the three values enclosed in `{{ ... }}` are replaced with the specifics for the particular job.