Tech Notes

Series Kubernetes & Helm from scratch · Part 3

Helm fundamentals and your first chart

Turn hand-written Kubernetes YAML into a Helm chart: templates, values, helpers, stable selector labels, and install, upgrade and rollback.

In part 2 we wrote a Deployment and a Service by hand and applied them with kubectl. That works for one app in one environment. The trouble starts when the same app needs to run in dev, staging and production with different replica counts, image tags, resource sizes and hostnames. Copying the YAML into three folders and editing each copy works for about a week, until a fix lands in one copy and not the others.

Helm fixes this by splitting a deployment into two parts: one set of templates that describe the shape of the objects, and small values files that hold whatever differs between environments. In this part we’ll build our first chart, charts/learning-chart, install it as a release called auth-dev, then upgrade it and roll it back. Everything we learn here gets reused when we write real charts for the backend and frontend in parts 9 and 10.

Four words to learn first

Chart A folder of templates plus default values and metadata. It's the package.
Release One installed copy of a chart in a cluster, with a name such as auth-dev. Install the same chart twice and you get two releases.
Values The settings fed into the templates: defaults in values.yaml, overridden per environment with -f or --set.
Repository Somewhere charts are published and downloaded from, like the Bitnami charts we'll use for PostgreSQL in part 7.

Helm itself is only a client. There’s no server component in the cluster: helm renders the templates on your laptop, sends the resulting manifests to the API server, and records what it installed as a Secret in the release’s namespace. That record is what makes helm history and helm rollback possible.

The same templates combined with a dev values file or a prod values file render two different sets of manifests, which Helm sends to the API server as separate releases. templates/shape of the objects values-dev.yaml values-prod.yaml helmrender on laptop release dev2 replicas release prod6 replicas APIserver
One set of templates, many environments. Only the values change; Helm does the rendering before anything reaches the cluster.

Create the chart

From the root of the project:

helm create charts/learning-chart

helm create scaffolds a working chart for a generic web app. It’s a good reference, but it contains far more than we need right now (an Ingress, an autoscaler, a ServiceAccount, a test pod), and reading all of it at once hides the ideas. So we’ll keep the structure and replace the contents with something small enough to understand line by line:

cd charts/learning-chart
rm -rf templates/*
touch templates/_helpers.tpl templates/deployment.yaml templates/service.yaml

The layout we’re left with:

charts/learning-chart/
├── Chart.yaml          # name, chart version, app version
├── values.yaml         # default values
├── .helmignore         # files to leave out when packaging
├── charts/             # dependencies (subcharts), empty for now
└── templates/
    ├── _helpers.tpl    # reusable snippets, renders nothing on its own
    ├── deployment.yaml
    └── service.yaml

Every file in templates/ is rendered and sent to the cluster, except files starting with an underscore, which only hold definitions for other templates to use.

Chart.yaml and values.yaml

Replace Chart.yaml with:

apiVersion: v2
name: learning-chart
description: A small chart for learning Helm
type: application
version: 0.1.0        # the chart's own version: bump it when the templates change
appVersion: "1.0"     # the version of the app it deploys

The two versions are separate on purpose. version tracks changes to the packaging, appVersion tracks the software inside. Changing a template without changing the app means bumping version only.

Now values.yaml, holding the same settings we hard-coded in part 2:

replicaCount: 2

image:
  repository: kicbase/echo-server
  tag: ""               # empty means "use the chart's appVersion"
  pullPolicy: IfNotPresent

service:
  type: ClusterIP
  port: 80

containerPort: 8080

resources:
  requests:
    cpu: 50m
    memory: 32Mi
  limits:
    cpu: 200m
    memory: 64Mi

Values are just a YAML tree. In templates we reach them through .Values, so image.repository becomes .Values.image.repository.

Go templating in five minutes

Helm templates are YAML with Go template actions in double curly braces. Those actions can read from a few built-in objects:

  • .Values: the merged values (defaults plus anything you override).
  • .Release: facts about this install, such as .Release.Name (auth-dev) and .Release.Namespace.
  • .Chart: the contents of Chart.yaml, such as .Chart.Name and .Chart.AppVersion.

Values can be piped through functions: {{ .Values.image.tag | default .Chart.AppVersion }} uses the tag if it’s set and the app version if not, and | quote wraps a value in quotes so YAML doesn’t turn 1.0 into a number.

Helpers: one definition, used everywhere

Labels appear in several places in every chart: on the Deployment, on the pod template, in the Deployment’s selector and in the Service’s selector. Writing them out each time is how they drift apart. Instead we define them once in templates/_helpers.tpl:

{{- define "learning-chart.fullname" -}}
{{- printf "%s-%s" .Release.Name .Chart.Name | trunc 63 | trimSuffix "-" }}
{{- end }}

{{- define "learning-chart.selectorLabels" -}}
app.kubernetes.io/name: {{ .Chart.Name }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}

{{- define "learning-chart.labels" -}}
helm.sh/chart: {{ printf "%s-%s" .Chart.Name .Chart.Version }}
{{ include "learning-chart.selectorLabels" . }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end }}
  • define names a snippet. Prefixing it with the chart name avoids clashes when charts are combined later, in the umbrella chart of part 11.
  • fullname builds auth-dev-learning-chart from the release and chart names. trunc 63 keeps it within the 63-character limit Kubernetes puts on names and labels, and trimSuffix "-" removes a trailing dash the cut might leave.
  • labels includes selectorLabels and adds more. The extra labels are where the difference between the two matters.

labels vs selectorLabels

selectorLabels hold only the stable name and instance and are used by the Deployment and Service selectors; labels add the chart and app versions, which change on upgrades, and go on metadata only. labelsmetadata on every object selectorLabelsapp.kubernetes.io/nameapp.kubernetes.io/instance helm.sh/chartapp.kubernetes.io/versionapp.kubernetes.io/managed-bychange on upgrade Deployment spec.selectorimmutable once created Service spec.selectorpicks which pods get traffic version in a selector?next upgrade fails: field is immutable
Selectors get only the labels that never change for the life of a release. Everything that changes on upgrade stays in metadata.

We saw in part 2 that a Deployment’s selector is immutable. If the selector included app.kubernetes.io/version, the first upgrade that changed appVersion would try to change the selector, and the API server would refuse the whole upgrade. So the split is:

  • selectorLabels: name and instance only. Together they identify “the pods of this release” and never change while the release exists. They go into spec.selector and into the Service’s selector.
  • labels: selectorLabels plus anything informational. They go on metadata.labels of every object and the pod template, where changing them is harmless and useful for filtering.

The templates

templates/deployment.yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "learning-chart.fullname" . }}
  labels:
    {{- include "learning-chart.labels" . | nindent 4 }}
spec:
  replicas: {{ .Values.replicaCount }}
  selector:
    matchLabels:
      {{- include "learning-chart.selectorLabels" . | nindent 6 }}
  template:
    metadata:
      labels:
        {{- include "learning-chart.labels" . | nindent 8 }}
    spec:
      containers:
        - name: {{ .Chart.Name }}
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          ports:
            - name: http
              containerPort: {{ .Values.containerPort }}
          readinessProbe:
            httpGet:
              path: /
              port: http
          livenessProbe:
            httpGet:
              path: /
              port: http
            initialDelaySeconds: 10
          resources:
            {{- toYaml .Values.resources | nindent 12 }}

templates/service.yaml:

apiVersion: v1
kind: Service
metadata:
  name: {{ include "learning-chart.fullname" . }}
  labels:
    {{- include "learning-chart.labels" . | nindent 4 }}
spec:
  type: {{ .Values.service.type }}
  selector:
    {{- include "learning-chart.selectorLabels" . | nindent 4 }}
  ports:
    - name: http
      port: {{ .Values.service.port }}
      targetPort: http

The . passed to include is the current context: it hands the helper the same .Values, .Release and .Chart the template sees. Without it the helper would have nothing to read.

include, nindent and the dash

Three small things in those templates do all the formatting work, and they’re the part of Helm that trips everyone up at first:

  1. include returns text Unlike Go's built-in template, its output can be piped into other functions. That's why Helm charts use include almost everywhere.
  2. nindent 4 adds a newline, then indents every line by 4 spaces The helper's output has no indentation of its own, and YAML depends on indentation, so the template decides where the block sits. The number must match the nesting depth at that spot: 4 under metadata.labels, 6 under matchLabels, 8 under the pod template's labels.
  3. {{- trims whitespace to the left including the newline before it. Combined with nindent's own leading newline, the result is exactly one line break and the right indentation. -}} does the same on the right, which is why the define lines in the helpers file don't leave blank lines behind.

toYaml .Values.resources does the same job for a whole subtree: it turns the resources map from the values back into YAML, and nindent 12 puts it under the container.

Render before you install

Helm can show exactly what it would send, without touching the cluster:

helm lint charts/learning-chart
helm template auth-dev charts/learning-chart --namespace apps

helm lint checks the chart’s structure and catches template errors. helm template prints the rendered manifests, with auth-dev as the release name. Read the output once: the labels should appear under each metadata, only the two selector labels under each selector, and the image should be kicbase/echo-server:1.0, filled in from appVersion because image.tag is empty.

Gotcha: an error such as mapping values are not allowed in this context almost always means an nindent number doesn't match the surrounding indentation, or a missing dash has left a stray newline. helm template with --debug prints the broken output so you can see where.

Install, upgrade, roll back

A release's history: revision 1 is the install with 2 replicas, revision 2 is an upgrade to 3 replicas, and a rollback creates revision 3 with the same settings as revision 1. rev 1helm installreplicas: 2 rev 2helm upgradereplicas: 3 rev 3helm rollback 1replicas: 2 again
A rollback never rewinds history. It copies an old revision forward as a new one, so the record of what happened stays intact.

Install the chart as release auth-dev in the apps namespace we created in part 2:

helm install auth-dev charts/learning-chart --namespace apps
helm list -n apps
kubectl get deploy,svc,pods -n apps -l app.kubernetes.io/instance=auth-dev

helm list shows the release at revision 1. The kubectl command uses the instance selector label to find everything belonging to this release, which is one practical payoff of consistent labels.

Now change something. For a quick experiment --set overrides one value on the command line:

helm upgrade auth-dev charts/learning-chart -n apps --set replicaCount=3
kubectl get pods -n apps -l app.kubernetes.io/instance=auth-dev
helm history auth-dev -n apps

A third pod appears, and the history shows revision 2. For anything you want to keep, put the overrides in a file and commit it, for example charts/learning-chart/values-dev.yaml containing replicaCount: 3, then pass -f charts/learning-chart/values-dev.yaml. Files listed with -f are merged over values.yaml in order, and --set wins over all of them. Note that helm upgrade starts from the chart defaults each time: an override you don’t pass again is dropped, unless you add --reuse-values.

Roll back to the first revision:

helm rollback auth-dev 1 -n apps
helm history auth-dev -n apps

The history now has a revision 3 described as a rollback to 1, and the pod count goes back to two. Helm keeps each revision as a Secret in the namespace, which you can see with kubectl get secrets -n apps -l owner=helm.

When you’re finished, remove the release and everything it created:

helm uninstall auth-dev -n apps
helm template Render locally and print. Nothing touches the cluster.
helm install / upgrade Render and apply, recording a new revision each time.
helm rollback Re-apply an earlier revision as a new one.
helm uninstall Delete every object the release created, and its history.

Takeaways

  • A chart is templates plus default values; a release is one named install of it, such as auth-dev.
  • Helm renders on your machine and stores each revision as a Secret in the release’s namespace.
  • Put shared snippets in _helpers.tpl and pull them in with include and nindent, matching the indentation of each spot.
  • {{- and -}} trim whitespace; most rendering errors are indentation or trimming mistakes, and helm template --debug shows them.
  • Selectors get only stable labels (name and instance); versions and chart labels stay in metadata.
  • Upgrades and rollbacks both add revisions, so helm history is a full record of what changed.

Next, in part 4, we build the Spring Boot authentication backend that our own charts will deploy.