Hooks & Lifecycle

๐Ÿ”ฅ Vibe Prompt

"Add Helm hooks: pre-install DB migration, post-install notification, pre-upgrade backup."

Hook Types

apiVersion: batch/v1
kind: Job
metadata:
  name: db-migrate
  annotations:
    "helm.sh/hook": pre-install,pre-upgrade
    "helm.sh/hook-weight": "-5"
    "helm.sh/hook-delete-policy": hook-succeeded
spec:
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: migration
          image: myapp:latest
          command: ["npm", "run", "migrate"]
---
apiVersion: v1
kind: Pod
metadata:
  name: notify
  annotations:
    "helm.sh/hook": post-install,post-upgrade
    "helm.sh/hook-weight": "10"
spec:
  restartPolicy: Never
  containers:
    - image: curlimages/curl
      command: ["curl", "-X", "POST", "https://hooks.slack.com/..."]

Hook Order (by weight)

-10  pre-install (backup)
 -5  pre-install (migration)
  0  install (main chart)
  5  post-install (verify)
 10  post-install (notify)

Lifecycle Best Practices

| Hook | Use Case | |------|----------| | pre-install | DB creation, schema setup | | post-install | Notification, cache warmup | | pre-upgrade | Backup, migration | | post-upgrade | Smoke test, rollback check | | pre-delete | Snapshot, cleanup | | post-delete | Notification |

Rollback Safety

annotations:
  "helm.sh/hook": pre-upgrade
  "helm.sh/hook-delete-policy": before-hook-creation

Complete Lifecycle

helm install โ†’ pre-install hooks โ†’ install โ†’ post-install hooks
helm upgrade โ†’ pre-upgrade hooks โ†’ upgrade โ†’ post-upgrade hooks
helm rollback โ†’ (re-runs upgrade hooks)
helm delete โ†’ pre-delete hooks โ†’ delete โ†’ post-delete hooks

Chapter Summary

  • Understand core concepts and principles
  • Master implementation methods and techniques
  • Familiar with common issues and solutions
  • Able to apply in real projects

Further Reading

  • Official documentation and API references
  • Open source examples on GitHub
  • Technical books and online courses
  • Community discussions and tech blogs

Implementation Example

Basic Example

# This section provides a complete implementation example

Steps

  1. Setup: Configure development environment
  2. Data: Prepare required data
  3. Implementation: Build core functionality
  4. Testing: Verify correctness
  5. Optimization: Improve performance

Common Errors

| Error Type | Cause | Solution | |------------|-------|----------| | Compilation | Syntax | Check code syntax | | Runtime | Environment | Verify dependencies installed | | Logic | Algorithm | Step-by-step debugging | | Performance | Efficiency | Use profilers |

Code Example

import sys

def main():
    print("Hello, World!")

if __name__ == "__main__":
    main()

References

  • Official documentation
  • API reference
  • Open source examples
  • Community discussions

Hook Weights and Execution Order

Hooks can run in a specific order using weights. Without weights, hooks run concurrently.

Weight System

| Weight Range | Execution Order | |-------------|----------------| | -100 to -1 | Before default (pre-hooks run first) | | 0 (default) | Default priority | | 1 to 100 | After default |

annotations:
  "helm.sh/hook": pre-install
  "helm.sh/hook-weight": "-5"

Hook Chain Example

pre-install (-10) โ†’ pre-install (-5) โ†’ pre-install (0) โ†’ install โ†’ post-install (0) โ†’ post-install (5)

Hook Deletion Policies

Control whether hook resources are deleted after execution.

| Policy | Behavior | |--------|----------| | before-hook-creation | Delete before new hook runs | | hook-succeeded | Delete only on success | | hook-failed | Delete only on failure |

annotations:
  "helm.sh/hook": post-install
  "helm.sh/hook-delete-policy": hook-succeeded

Practical Use Cases

Database Migration

apiVersion: batch/v1
kind: Job
metadata:
  name: {{ include "myapp.fullname" . }}-migrate
  annotations:
    "helm.sh/hook": post-install,post-upgrade
    "helm.sh/hook-weight": "-5"
    "helm.sh/hook-delete-policy": hook-succeeded
spec:
  template:
    spec:
      restartPolicy: Never
      containers:
      - name: migrate
        image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
        command: ["node", "scripts/migrate.js"]
        env:
        - name: DATABASE_URL
          valueFrom:
            secretKeyRef:
              name: {{ .Values.database.existingSecret }}
              key: url

Pre-Install Validation

apiVersion: batch/v1
kind: Job
metadata:
  name: {{ include "myapp.fullname" . }}-validate
  annotations:
    "helm.sh/hook": pre-install,pre-upgrade
    "helm.sh/hook-weight": "-10"
    "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
spec:
  template:
    spec:
      restartPolicy: Never
      containers:
      - name: validate
        image: bitnami/kubectl:latest
        command:
        - sh
        - -c
        - |
          kubectl get namespace {{ .Values.global.namespace }} || exit 1
          kubectl get secret {{ .Values.database.existingSecret }} || exit 1

Cleanup Job

apiVersion: batch/v1
kind: Job
metadata:
  name: {{ include "myapp.fullname" . }}-cleanup
  annotations:
    "helm.sh/hook": pre-delete
    "helm.sh/hook-weight": "0"
    "helm.sh/hook-delete-policy": hook-succeeded
spec:
  template:
    spec:
      restartPolicy: Never
      containers:
      - name: cleanup
        image: bitnami/kubectl:latest
        command:
        - sh
        - -c
        - |
          kubectl delete pvc -l app.kubernetes.io/instance={{ .Release.Name }}

Testing Hooks Locally

# Dry run to see hook order
helm install myapp ./myapp --dry-run

# Install with hooks
helm install myapp ./myapp

# Check hook jobs
kubectl get jobs -n default
kubectl logs job/myapp-migrate

# Upgrade triggers hooks again
helm upgrade myapp ./myapp

Common Mistakes

| Mistake | Consequence | Fix | |---------|-------------|-----| | No delete policy | Old jobs accumulate | Add hook-delete-policy | | Wrong hook type | Runs at wrong time | Verify hook annotation | | Missing weight | Concurrent execution | Add weight for ordering | | No error handling | Failed hooks ignored | Add activeDeadlineSeconds | | Heavy dependencies | Slow installation | Keep hooks lightweight |

Summary

Helm hooks enable lifecycle automation โ€” running jobs before, after, or during releases. Use weights for ordering and delete policies to clean up.

Key takeaways:

  • Helm hooks: pre/post install, upgrade, rollback, delete, test |
  • Hooks are Kubernetes resources (Jobs, Pods) with special annotations |
  • Hook weights control execution order (-100 to 100) |
  • Delete policies prevent resource accumulation |
  • Common hooks: DB migration, validation, backup, cleanup |
  • Test hooks verify release functionality |
  • Always handle hook failures gracefully |

What's Next: Security Best Practices

The next chapter covers Helm security best practices.

Unlock Full Tutorial

This chapter is paid content. Join the project to unlock over 5000 words of deep analysis, including 10+ god-tier Prompts and real Source Code examples!