Skip to content
Tutorials Center
My learning

Topics

Lesson 69 of 78 ยท Projects

Project: Package an App as a Helm Chart

Turn plain manifests into a Helm chart with helpers, dev and prod values, a conditional ingress and a test, with a runnable Python renderer to see how it works.

Plain manifests work well until you need the same app in three places. Development wants one replica and a test image, production wants five replicas, an Ingress and an autoscaler, and soon you are copying YAML and editing it by hand. Helm solves this by turning your manifests into a chart: a folder of templates plus a set of default values that each environment can override.

In this project you package a small web app as a chart, give it separate values for development and production, add a helper, a conditional Ingress and a test, and read the commands that install it. Helm cannot run on this site, so the chart files and helm commands are read-only. To see how rendering really works, you will run a small Python renderer that mimics the core of Helm's template language. It is a stand-in: Helm uses Go templates with many more functions. If Helm is new to you, start with Helm: Charts and Releases and Writing Helm Charts.

From manifests to a chart

Templates YAML with holes in it.
Values The numbers that fill the holes.
Release One installed copy of a chart.

Same templates, different values, different environments.

1 / 2

The chart layout

Run helm create web and you get a generated chart. For this project we write our own, much smaller, version. This is the folder:

TEXT
web/
  Chart.yaml
  values.yaml
  values-dev.yaml
  values-prod.yaml
  values.schema.json
  templates/
    _helpers.tpl
    deployment.yaml
    service.yaml
    ingress.yaml
    hpa.yaml
    NOTES.txt
    tests/
      test-connection.yaml

Chart.yaml describes the chart itself. version is the version of the chart (bump it whenever templates change), while appVersion is the version of the application inside, which we will use as the default image tag.

YAML
apiVersion: v2
name: web
description: A small web application
type: application
version: 0.1.0
appVersion: "1.4.0"

values.yaml holds the defaults, and every key a template reads should have a sensible default here.

YAML
replicaCount: 1

image:
  repository: registry.example.com/shop/web
  tag: ""            # empty means: use .Chart.AppVersion
  pullPolicy: IfNotPresent

service:
  port: 80

ingress:
  enabled: false
  host: web.local

autoscaling:
  enabled: false
  minReplicas: 2
  maxReplicas: 6
  targetCPUUtilizationPercentage: 70

resources:
  requests:
    cpu: 50m
    memory: 64Mi
  limits:
    memory: 128Mi

Environment files contain only what differs. Helm merges them over the defaults, so these files stay short and readable:

YAML
# values-prod.yaml
replicaCount: 3
image:
  pullPolicy: Always
ingress:
  enabled: true
  host: shop.example.com
autoscaling:
  enabled: true
  maxReplicas: 10
resources:
  requests:
    cpu: 200m
    memory: 256Mi
  limits:
    memory: 512Mi
YAML
# values-dev.yaml
resources:
  requests:
    cpu: 20m
    memory: 32Mi

The merge is recursive for maps and replaces whole lists. That rule surprises many people: if a values file sets a list, it replaces the default list instead of adding to it. Only the values you set in a file are changed; everything else keeps its default. You can see this rule in action below.

Python Merging values files

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check the output: minReplicas and the repository survive from the defaults, maxReplicas is overridden, and extraArgs contains only --json, because lists are replaced.

Templates and the helper

Repeating names and labels in every template is error-prone, so charts put them in templates/_helpers.tpl. Files starting with an underscore are not rendered as manifests; they only define named snippets.

YAML
{{- define "web.fullname" -}}
{{- if contains .Chart.Name .Release.Name }}
{{- .Release.Name | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- printf "%s-%s" .Release.Name .Chart.Name | trunc 63 | trimSuffix "-" }}
{{- end }}
{{- end }}

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

Naming objects after the release lets you install the chart several times into one namespace (for example web-blue and web-green) without name collisions. Kubernetes names are limited to 63 characters in many places, hence trunc 63.

Now the Deployment template. It reads values, uses the helper and falls back to the chart's appVersion when no tag is given:

YAML
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "web.fullname" . }}
  labels:
    {{- include "web.selectorLabels" . | nindent 4 }}
spec:
  {{- if not .Values.autoscaling.enabled }}
  replicas: {{ .Values.replicaCount }}
  {{- end }}
  selector:
    matchLabels:
      {{- include "web.selectorLabels" . | nindent 6 }}
  template:
    metadata:
      labels:
        {{- include "web.selectorLabels" . | nindent 8 }}
    spec:
      containers:
        - name: web
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          ports:
            - name: http
              containerPort: 8080
          resources:
            {{- toYaml .Values.resources | nindent 12 }}

Two details matter here. First, when the HPA is enabled the template omits replicas, so that helm upgrade does not reset the replica count that the autoscaler chose. Second, nindent starts a new line and indents it, which is how nested YAML stays valid; wrong indentation is the most common template bug.

The Ingress and the autoscaler are wrapped in if blocks, so they exist only when the values say so:

YAML
{{- if .Values.ingress.enabled }}
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: {{ include "web.fullname" . }}
spec:
  rules:
    - host: {{ .Values.ingress.host | quote }}
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: {{ include "web.fullname" . }}
                port:
                  number: {{ .Values.service.port }}
{{- end }}

A renderer you can run

The real engine is Helm's Go template library. The stand-in below supports only four things: {{ .Values.x.y }} lookups, the quote and default pipes, include "web.fullname" . for one helper, and a non-nested if block. That is enough to watch the idea work.

Python A mini template renderer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The dev release prints one object and falls back to image tag 1.4.0 from appVersion. The prod release prints two objects, because ingress.enabled is true, and uses the explicit tag. With the real tool you would see the same behavior by running helm template.

Testing the chart

Helm gives you three levels of checking, from cheap to thorough:

Terminal
helm lint ./web -f web/values-prod.yaml
helm template shop ./web -f web/values-prod.yaml | less
helm install shop ./web -f web/values-prod.yaml --dry-run --debug

helm lint catches structural mistakes. helm template renders locally without a cluster, so you can diff or validate the output. A dry-run install also asks the API server to validate the objects. After a real install, helm test runs any pod annotated as a test hook and reports pass or fail:

YAML
apiVersion: v1
kind: Pod
metadata:
  name: "{{ include "web.fullname" . }}-test"
  annotations:
    "helm.sh/hook": test
spec:
  restartPolicy: Never
  containers:
    - name: probe
      image: busybox:1.37
      command: ["wget"]
      args: ["-qO-", "http://{{ include "web.fullname" . }}:{{ .Values.service.port }}/healthz"]

A values.schema.json file adds another safety net: Helm validates the merged values against it on install, upgrade, lint and template, so replicaCount: "three" fails before any object is created. The last stand-in does a small version of that check.

Python Validating values like a schema

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Installing and operating a release

Installing creates a release: a named instance of the chart whose state Helm stores as a Secret in the namespace. These are the commands you will use all the time:

Terminal
# first install or upgrade, same command both times
helm upgrade --install shop ./web -n shop --create-namespace -f web/values-prod.yaml --set image.tag=1.5.0

helm list -n shop
helm history shop -n shop
helm test shop -n shop

# something went wrong: go back to revision 1
helm rollback shop 1 -n shop

# package and publish
helm package ./web

A rollback restores the previous rendered manifests; it does not undo changes to data. Keep chart version and app version honest, and put the chart in version control next to the code. In the next project you will let a pipeline run these steps for you.

Add a checksum annotation such as checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }} to the pod template when the app reads a ConfigMap. The pods then restart automatically when the ConfigMap changes, because the pod template changed.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between a chart's version and its appVersion?

    The chart version changes when templates or defaults change. The appVersion describes the application inside; here it is the default image tag.
  2. 2. A values-prod.yaml sets extraArgs to a list with one item. The default values.yaml has a list with three items. What does the merged value contain?

    Helm merges maps recursively, but a list is replaced as a whole by the later file.
  3. 3. Why does the Deployment template skip replicas when autoscaling is enabled?

    If the chart sets replicas, each upgrade would overwrite the HPA's decision. Leaving the field out hands control to the autoscaler.
  4. 4. Which command renders the chart locally without contacting a cluster?

    helm template prints the rendered manifests to standard output, which is ideal for reviews, diffs and offline validation.

Summary

  • A chart is templates plus default values; each environment adds a small values file with only the differences.
  • Values merge in order: chart defaults, values files, then --set; maps merge recursively and lists are replaced.
  • Helpers in _helpers.tpl keep names and labels consistent, and if blocks make objects such as Ingress and HPA optional.
  • Check charts with helm lint, helm template, a dry run, a values schema and helm test.
  • A release can be upgraded and rolled back by revision; the Python renderer here is a simplified model of Helm's engine.

Next, automate delivery end to end: Project: CI/CD Pipeline to Kubernetes.