Pre/Post Install Hooks for Migrations and Setup
Advanced18 min
Use Helm lifecycle hooks to run database migrations, seed data, send notifications, and perform cleanup tasks during chart install and upgrade operations.
Prerequisites
- -Helm 3 installed
- -Understanding of Kubernetes Jobs
- -An existing Helm chart
Steps
1
Create a pre-install hook for database migration
Define a Job that runs before the main application is deployed.
$ cat > myapp/templates/pre-install-migration.yaml << 'EOF'
apiVersion: batch/v1
kind: Job
metadata:
name: {{ include "myapp.fullname" . }}-migrate
annotations:
"helm.sh/hook": pre-install,pre-upgrade
"helm.sh/hook-weight": "0"
"helm.sh/hook-delete-policy": hook-succeeded
spec:
template:
spec:
restartPolicy: Never
containers:
- name: migrate
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
command: ["npm", "run", "db:migrate"]
envFrom:
- secretRef:
name: {{ include "myapp.fullname" . }}-db-secret
EOF
hook-weight controls execution order when multiple hooks exist. Lower weights run first.
2
Add a post-install notification hook
Send a Slack notification after a successful deployment.
$ cat > myapp/templates/post-install-notify.yaml << 'EOF'
apiVersion: batch/v1
kind: Job
metadata:
name: {{ include "myapp.fullname" . }}-notify
annotations:
"helm.sh/hook": post-install,post-upgrade
"helm.sh/hook-weight": "10"
"helm.sh/hook-delete-policy": hook-succeeded,hook-failed
spec:
template:
spec:
restartPolicy: Never
containers:
- name: notify
image: curlimages/curl:latest
command:
- sh
- -c
- |
curl -X POST "$SLACK_WEBHOOK" -H 'Content-type: application/json' \
-d '{"text": "Deployed {{ include "myapp.fullname" . }} v{{ .Chart.AppVersion }}"}'
env:
- name: SLACK_WEBHOOK
valueFrom:
secretKeyRef:
name: slack-webhook
key: url
EOF
3
Verify hook annotations
Render templates to confirm hooks are correctly annotated.
$ helm template myapp/ | grep -A5 'helm.sh/hook'
4
Test hooks with a dry run
Simulate the install to see hook execution order.
$ helm install test myapp/ --dry-run --debug 2>&1 | grep -E '(hook|HOOK|Job)'
Hooks with 'hook-delete-policy: hook-succeeded' are automatically deleted after success. Use 'before-hook-creation' to delete the previous hook resource before creating a new one on upgrade.
5
Debug a failed hook
Inspect hook Job logs when a deployment is stuck.
$ kubectl get jobs -n production -l 'app.kubernetes.io/managed-by=Helm' && kubectl logs job/<release>-migrate -n production
Full Script
FAQ
Discussion
Loading comments...