# Hooks and Chart Tests — Helm

Source: https://www.skillbyai.com/en/helm/a-hooks

> Run jobs at specific points in a release lifecycle and test a release.

## Doing work before or after the main install

**Hooks** are ordinary templates with a `helm.sh/hook` annotation that Helm runs at specific points rather than as part of the main resources: `pre-install`, `post-install`, `pre-upgrade`, `post-upgrade`, `pre-delete`, `post-delete`, `pre-rollback`, `post-rollback` and `test`. A typical use is a **database migration Job** as a `pre-upgrade` hook. Helm waits for hook Jobs to complete; if a hook fails, the release operation fails. **`helm.sh/hook-weight`** orders hooks (lower first), and **`helm.sh/hook-delete-policy`** controls cleanup: `before-hook-creation` (the default: delete the previous hook object before creating a new one), `hook-succeeded` and `hook-failed`. Hook resources are not managed as part of the release, so they are not removed by `helm uninstall` unless a delete policy does it. **Chart tests** are pods annotated `helm.sh/hook: test`, run on demand by `helm test RELEASE`, for example to call the service's health endpoint.

## A migration Job as a pre-upgrade hook

Runs before new pods roll out; deleted once it succeeds.

```yaml
apiVersion: batch/v1
kind: Job
metadata:
  name: {{ include "shop-api.fullname" . }}-migrate
  annotations:
    "helm.sh/hook": pre-install,pre-upgrade
    "helm.sh/hook-weight": "0"
    "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
spec:
  backoffLimit: 1
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: migrate
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
          command: ["./manage", "migrate", "--no-input"]
          envFrom:
            - secretRef:
                name: shop-db-credentials
```

## Prep before the kitchen opens

Pre-upgrade hooks are the morning prep before the restaurant opens: chop vegetables and update the menu board first, then let customers in. If the prep fails, the doors stay shut.

**Quiz:** Which annotation makes a pod run only when you execute `helm test`?

- [ ] helm.sh/hook: post-install
- [ ] helm.sh/hook-weight: test
- [ ] helm.sh/resource-policy: keep
- [x] helm.sh/hook: test

*Answer:* helm.sh/hook: test. Pods annotated with helm.sh/hook: test run on demand through helm test.
