Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 452 of 8027. Package Management and AutomationFree lesson

Automating Deployments with Helm Hooks

Learners will implement Helm hooks to trigger specific actions at different stages of the release process, such as database migrations or cleanup tasks.

In this lesson, you will learn how to automate operational tasks during your Helm deployment lifecycle using Helm Hooks.

While standard Helm manifests define the state of your application (like Deployments or Services), sometimes you need to perform actions—such as running database migrations before a new version rolls out or cleaning up temporary resources after an upgrade. This is exactly what Helm Hooks are for.

How Hooks Work

Hooks are standard Kubernetes manifest files that include a specific annotation: helm.sh/hook. This annotation tells Helm to manage the resource differently. Instead of just creating the object, Helm executes it at a designated phase in the release lifecycle.

For example, to run a database migration job immediately before a new version of your application is deployed, you define a Job with the pre-install and pre-upgrade hooks:

apiVersion: batch/v1
kind: Job
metadata:
  name: "db-migration"
  annotations:
    "helm.sh/hook": "pre-install,pre-upgrade"
    "helm.sh/hook-delete-policy": "hook-succeeded"
spec:
  template:
    spec:
      containers:
      - name: migration-tool
        image: my-repo/migration-image:latest
      restartPolicy: Never

Controlling the Lifecycle

Beyond just triggering the task, you can control how the hook behaves with helm.sh/hook-weight and helm.sh/hook-delete-policy.

  • Hook Weight: Use a weight (e.g., "helm.sh/hook-weight": "1") to define the order of execution if you have multiple hooks in the same phase.
  • Delete Policy: Since hooks create actual Kubernetes resources, they stay in your cluster after completion. Using hook-succeeded tells Helm to automatically remove the job once it completes successfully, keeping your cluster clean and preventing "AlreadyExists" errors on subsequent deployments.

By offloading these procedural tasks to Helm, you ensure that your infrastructure state and your data state remain perfectly synchronized without requiring manual intervention or separate CI/CD scripts.

Key Takeaway: Helm Hooks allow you to inject procedural logic into your declarative release process, ensuring that critical tasks like migrations or cleanups run automatically at the precise moment your deployment requires them.