Skip to content

Helm Hooks & Tests

Helm Hooks

Hooks 允许在 Helm 生命周期的特定时间点执行操作。

Hook 类型

Hook触发时机
pre-install安装前
post-install安装后
pre-upgrade升级前
post-upgrade升级后
pre-rollback回滚前
post-rollback回滚后
pre-delete删除前
post-delete删除后
testhelm test

数据库迁移 Hook

yaml
# templates/hooks/db-migrate.yaml
apiVersion: batch/v1
kind: Job
metadata:
  name: {{ include "my-app.fullname" . }}-db-migrate
  annotations:
    "helm.sh/hook": pre-upgrade,pre-install
    "helm.sh/hook-weight": "-5"           # 执行顺序(数字越小越先执行)
    "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
spec:
  template:
    spec:
      restartPolicy: Never
      containers:
      - name: migrate
        image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
        command: ["python", "manage.py", "migrate"]
        env:
        - name: DATABASE_URL
          valueFrom:
            secretKeyRef:
              name: {{ include "my-app.fullname" . }}-db-secret
              key: url

清理 Hook

yaml
# templates/hooks/cleanup.yaml
apiVersion: batch/v1
kind: Job
metadata:
  name: {{ include "my-app.fullname" . }}-cleanup
  annotations:
    "helm.sh/hook": pre-delete
    "helm.sh/hook-delete-policy": hook-succeeded
spec:
  template:
    spec:
      restartPolicy: Never
      containers:
      - name: cleanup
        image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
        command: ["python", "cleanup.py"]

Hook 删除策略

策略说明
before-hook-creation创建新 Hook 前删除旧的
hook-succeededHook 成功后删除
hook-failedHook 失败后删除

Helm Test

yaml
# templates/tests/test-api.yaml
apiVersion: v1
kind: Pod
metadata:
  name: "{{ include "my-app.fullname" . }}-test-api"
  annotations:
    "helm.sh/hook": test
    "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
spec:
  containers:
  - name: test
    image: curlimages/curl:8.5.0
    command:
    - sh
    - -c
    - |
      # 测试健康检查
      curl -f http://{{ include "my-app.fullname" . }}:{{ .Values.service.port }}/healthz || exit 1
      # 测试 API
      curl -f http://{{ include "my-app.fullname" . }}:{{ .Values.service.port }}/api/v1/status || exit 1
      echo "所有测试通过!"
  restartPolicy: Never
bash
# 运行测试
helm test my-release -n production --logs

本站内容由 褚成志 整理编写,仅供学习参考