Using helm hooks to when certain objects are created

3 min read

Sometimes when we are writing a helm chart we realize that we have some parts of the task that need to be performed before of after deploying certain objects. We can also need to execute some Jobs in order to, for example, update the database, but not continuously, just when we update the application.

To handle this kind of situations we can use helm hooks

A helm hook it's just a regular Kubernetes object with some extra annotations. For example:

apiVersion: batch/v1
kind: Job
metadata:
  name: "sql-init"
  labels:
    app: "init-psql"
  annotations:
    "helm.sh/hook": "pre-install,pre-upgrade"
    "helm.sh/hook-delete-policy": "before-hook-creation"
    "helm.sh/hook-weight": "0"
spec:
  template:
    metadata:
      labels:
        component: init-sql
    spec:
      volumes:
      - name: init-db-scripts
        configMap:
          name: "init-db-scripts"
      containers:
      - name: check-indexes
        image: "postgres:10"
        command:
        - sh
        - "-x"
        - "/opt/scripts/init-db.sh"
        volumeMounts:
        - name: init-db-scripts
          mountPath: /opt/scripts

Let's take a look at these annotations

helm.sh/hook

The helm.sh/hook specifies the ordering we want for this objects:

  • pre-install: To be executed after templates are rendered, but before any resources are created in Kubernetes
  • post-install: To be executed after all resources are loaded into Kubernetes
  • pre-delete: To be executed on a deletion request before any resources are deleted from Kubernetes
  • post-delete: To be executed on a deletion request after all of the release's resources have been deleted
  • pre-upgrade: To be executed on an upgrade request after templates are rendered, but before any resources are updated
  • post-upgrade: To be executed on an upgrade request after all resources have been upgraded
  • pre-rollback: To be executed on a rollback request after templates are rendered, but before any resources are rolled back
  • post-rollback: To be executed on a rollback request after all resources have been modified
  • test: To be executed when we run helm test

So, on the example above this object would be created on before the resources are created (pre-install) or updated (pre-update)

helm.sh/hook-delete-policy

The helm.sh/hook-delete-policy let us configure what to do with the resources that the hook creates:

  • before-hook-creation: It deletes the previous resource before running the hook again
  • hook-succeeded: It deletes the resource after the hook is finishes successfully
  • hook-failed: It deletes the resource if the hook failed

helm.sh/hook-weight

Finally, if we have several hooks, with helm.sh/hook-weight we set the order we want them to be applied


Posted on 19/08/2021

Categories