Run a database migration before an apply
Run a schema migration as a Kubernetes Job that must finish before new code starts, decide what a failure does, and decide whether a rollback runs an undo.
The situation
payments-api keeps its schema in a database. A release that needs a new column must run migrate up first, and the new pods must not start until it succeeds. Wardn runs Kubernetes Jobs before the first wave of an apply, in the deployment's namespace, and stops the apply if one fails (Jobs and waves).
Three properties of these jobs decide the setup:
- A job is a delivery setting, not part of the snapshot. It is not rendered from git and does not change with a push. You set it on the deployment, and it takes effect with the next apply.
- A before job runs on every apply, including a sync you start by hand and a drift revert, which apply the snapshot again. The migration command must be a no-op when the schema is current.
- A rollback never repeats a forward job. In a restore or an automatic rollback, a job with an undo job runs the undo job instead, and a job with none is skipped.
Repository layout
The app is the three manifests in deploy/, a plain-manifest app as in Deploy your first app. The migration is not one of them: do not commit a Job object next to the Deployment. Wardn would apply it as an ordinary object, once, and leave it behind, and a Job's pod template cannot be changed by a later apply.
Settings
The cluster side
The job runs as the deployment's service account, wardn-deployer. It needs the right to create and read Jobs, pods and pod logs in the namespace; the built-in admin role has them (Connect a cluster). Keep the database password out of git and out of the job: create the Secret in the cluster, and let the job read it.
kubectl -n payments create secret generic payments-db \
--from-literal=DATABASE_URL='postgres://payments:[email protected]/payments'The job
Jobs are part of the delivery settings, which are replaced as a whole. In the web app, open the deployment › Settings and find Jobs. Choose Add job, set Job name migrate, Runs Before deploy, App Every app, If it fails Stop, don't deploy, paste the Job as JSON and choose Save delivery settings. The web app does not set the timeout or an undo job, so the API is used here:
api() { curl -fsS -H "Authorization: Bearer $WARDN_TOKEN" -H 'Content-Type: application/json' "$@"; }
# The same Job for any tag. $2 is the migrate command: up or down.
job() {
jq -n --arg tag "$1" --arg cmd "$2" '{
apiVersion: "batch/v1", kind: "Job",
spec: {template: {spec: {restartPolicy: "Never", containers: [{
name: "migrate", image: ("ghcr.io/example/payments-api:" + $tag), args: ["migrate", $cmd],
envFrom: [{secretRef: {name: "payments-db"}}]}]}}}}'
}
TAG=1.9.0
api "$WARDN_API_URL/api/v1/deployments/$DEPLOYMENT_ID/settings" \
| jq --argjson up "$(job "$TAG" up)" '
del(.delivery.updatedAt)
| .delivery.beforeJobs = [{name: "migrate", failurePolicy: "stop", timeoutSeconds: 600, job: $up}]' \
| api -X PUT "$WARDN_API_URL/api/v1/deployments/$DEPLOYMENT_ID/settings" -d @-Writing settings needs deployment:manage. timeoutSeconds is 0 to 3600 and zero means five minutes.
Release in the right order
Because the job's image is a setting and the app's image is in git, order matters. Point the job at the new tag first, then push the commit that uses it:
TAG=1.10.0 # then run the settings call above again with this tag
git commit -am "Release payments-api 1.10.0" && git push origin mainIf you push first, the apply runs the old migration against the new code's expectations. Use an immutable version tag for the job: Wardn runs the image as written and does not pin it to a digest.
What a failure does
failurePolicy is stop above. A failed or timed-out before job ends the apply: nothing is applied, no wave starts, and the old version keeps running against the old schema. The last 30 lines of the job's log are kept with the run, so you can read the reason without cluster access. Fix the migration, push, and the next apply runs it again.
roll_back also restores the last snapshot that applied, which only helps if that snapshot's code works with whatever schema the half-run migration left. Choose it only for migrations that are transactional.
Going back across a migration
On a restore, the forward job is skipped, so a rollback does not run migrate up again. Decide how the schema follows:
| Approach | How |
|---|---|
| Backward-compatible migrations (recommended) | Add columns before the code that uses them, drop them a release later. The previous snapshot runs against the newer schema, and no undo job is needed. |
| An undo job | Add an undoJob next to job, as below. On any restore or automatic rollback, migrate down runs in place of migrate up, before the old snapshot is applied. |
api "$WARDN_API_URL/api/v1/deployments/$DEPLOYMENT_ID/settings" \
| jq --argjson up "$(job "$TAG" up)" --argjson down "$(job "$TAG" down)" '
del(.delivery.updatedAt)
| .delivery.beforeJobs = [{name: "migrate", failurePolicy: "stop", timeoutSeconds: 600, job: $up, undoJob: $down}]' \
| api -X PUT "$WARDN_API_URL/api/v1/deployments/$DEPLOYMENT_ID/settings" -d @-The undo job runs on every rollback of this deployment, including a restore to a snapshot that ran on the same schema. If migrate down removes the latest migration unconditionally, it removes one the old code needs. Use an undo job only when your tool's down step is safe to run at that point and does exactly one step.
The restore preflight warns with migration.older only for a Job object that is part of a snapshot and carries the annotation wardn.dev/schema-migration: "true". A job configured in the delivery settings is not part of a snapshot, so the preflight does not warn about it. Read the findings, and check yourself that the older code fits the current schema.
Check that it worked
Push a commit and watch the apply. In the web app, the app's Jobs tab lists the job with Runs and Last run (Succeeded or Failed, and the snapshot). With the API:
api "$WARDN_API_URL/api/v1/deployments/$DEPLOYMENT_ID/job-runs" \
| jq '.items[:5][] | {name, phase, status, snapshotId, error}'
kubectl -n payments get jobsYou should see a run with phase: before and status: succeeded for the snapshot, and a Job migrate-xxxxx that completed. To see a failure, set the job's argument to something that exits non-zero and push: the run is failed with the log tail in error, the deployment shows Apply failed and the pods are untouched.
Next
Jobs and waves
The order of an apply, timeouts, failure policies and undo jobs.
Restore and rollback
The preflight and what a restore runs.
Recover from a bad change
Cause a bad release and go back, step by step.
Related: Deployment settings, Sync and arrival, Secret references.
One app on every cluster in an environment
Deploy a cluster add-on once, to an environment that selects its clusters by label, and have it follow clusters as they come and go.
Health rule for a custom resource
Tell Wardn when a cert-manager Certificate is healthy and when it has failed, with a CEL health rule on the deployment.