TExcelTAD
Home › Kubernetes Packaging: Helm & Kustomize › Mini Project: Packaging linkly

Mini Project: Packaging linkly

Time to put the course together: package linkly as a real, parameterised Helm chart, publish it to a registry, and deploy it to staging and production with Kustomize overlays, with everything linted, rendered and validated offline before any cluster sees it.

The brief

Requirement Where
a chart with Deployment, Service, ConfigMap, test, NOTES chart/linkly/templates/
routing through a Gateway API HTTPRoute, or an Ingress for a maintained controller on clusters without Gateway API (never both) httproute.yaml, ingress.yaml
an HPA that owns the replica count when enabled hpa.yaml, deployment.yaml
resource requests and limits, non-root, read-only root filesystem values.yaml, deployment.yaml
the database URL from an existing Secret, never from values deployment.yaml
a values schema that rejects typos and bad types values.schema.json
the chart versioned and pushed to an OCI registry helm package, helm push
staging and production as Kustomize overlays rendering the published chart deploy/overlays/*
a production-only change the chart doesn't expose a Kustomize component
every output valid for Kubernetes and Gateway API kubeconform -strict

The session

The session creates every file with heredocs, then runs the whole pipeline. It's long because it is the complete project; the walkthrough below goes through it part by part.

bash · try it yourself
# ---------- Part 1: the chart ----------
mkdir -p chart/linkly/templates/tests && cd chart/linkly
cat > Chart.yaml <<'EOF'
apiVersion: v2
name: linkly
description: linkly, a link shortener (Go, PostgreSQL, Redis)
type: application
version: 0.0.0-dev
appVersion: "0.0.0-dev"
kubeVersion: ">= 1.30.0-0"
icon: https://example.com/linkly.svg
maintainers: [{name: Platform Team, email: platform@example.com}]
EOF
cat > values.yaml <<'EOF'
replicaCount: 2
image:
  repository: ghcr.io/acme/linkly
  tag: ""                 # defaults to the chart's appVersion
  pullPolicy: IfNotPresent
config:
  logLevel: info
  baseUrl: https://lnk.example.com
  redisAddr: linkly-redis:6379
database:
  existingSecret: linkly-db  # a Secret with key "url", created outside the chart
service:
  port: 80
httpRoute:
  enabled: true
  parentRefs: [{name: public, namespace: gateway-system}]
  hostnames: [lnk.example.com]
ingress:
  enabled: false
  className: ""
  host: lnk.example.com
  tlsSecret: ""
autoscaling:
  enabled: false
  minReplicas: 2
  maxReplicas: 10
  targetCPUUtilizationPercentage: 70
resources:
  requests: {cpu: 100m, memory: 64Mi}
  limits: {memory: 128Mi}
podAnnotations: {}
EOF
cat > values.schema.json <<'EOF'
{
  "$schema": "https://json-schema.org/draft-07/schema#",
  "type": "object",
  "additionalProperties": false,
  "properties": {
    "replicaCount": {"type": "integer", "minimum": 1},
    "image": {"type": "object", "additionalProperties": false, "properties": {
      "repository": {"type": "string", "minLength": 1},
      "tag": {"type": "string"},
      "pullPolicy": {"enum": ["Always", "IfNotPresent", "Never"]}}},
    "config": {"type": "object", "additionalProperties": false,
      "required": ["logLevel", "baseUrl", "redisAddr"], "properties": {
      "logLevel": {"enum": ["debug", "info", "warn", "error"]},
      "baseUrl": {"type": "string", "pattern": "^https?://"},
      "redisAddr": {"type": "string"}}},
    "database": {"type": "object", "additionalProperties": false, "required": ["existingSecret"],
      "properties": {"existingSecret": {"type": "string", "minLength": 1}}},
    "service": {"type": "object", "properties": {"port": {"type": "integer"}}},
    "httpRoute": {"type": "object", "properties": {"enabled": {"type": "boolean"},
      "parentRefs": {"type": "array", "minItems": 1}, "hostnames": {"type": "array", "items": {"type": "string"}}}},
    "ingress": {"type": "object", "properties": {"enabled": {"type": "boolean"}, "className": {"type": "string"},
      "host": {"type": "string"}, "tlsSecret": {"type": "string"}}},
    "autoscaling": {"type": "object", "properties": {"enabled": {"type": "boolean"},
      "minReplicas": {"type": "integer", "minimum": 1}, "maxReplicas": {"type": "integer", "minimum": 1},
      "targetCPUUtilizationPercentage": {"type": "integer", "minimum": 1, "maximum": 100}}},
    "resources": {"type": "object"},
    "podAnnotations": {"type": "object", "additionalProperties": {"type": "string"}}
  }
}
EOF
cat > templates/_helpers.tpl <<'EOF'
{{- define "linkly.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 "linkly.selectorLabels" -}}
app.kubernetes.io/name: {{ .Chart.Name }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}
{{- define "linkly.labels" -}}
{{ include "linkly.selectorLabels" . }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
helm.sh/chart: {{ printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" }}
{{- end }}
EOF
cat > templates/configmap.yaml <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
data:
  LISTEN_ADDR: ":8080"
  LOG_LEVEL: {{ .Values.config.logLevel | quote }}
  BASE_URL: {{ .Values.config.baseUrl | quote }}
  REDIS_ADDR: {{ .Values.config.redisAddr | quote }}
EOF
cat > templates/deployment.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
spec:
  {{- if not .Values.autoscaling.enabled }}
  replicas: {{ .Values.replicaCount }}
  {{- end }}
  selector:
    matchLabels: {{- include "linkly.selectorLabels" . | nindent 6 }}
  template:
    metadata:
      labels: {{- include "linkly.selectorLabels" . | nindent 8 }}
      annotations:
        checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum | trunc 16 }}
        {{- with .Values.podAnnotations }}{{ toYaml . | nindent 8 }}{{ end }}
    spec:
      securityContext: {runAsNonRoot: true, runAsUser: 65532, seccompProfile: {type: RuntimeDefault}}
      containers:
        - name: linkly
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          ports: [{name: http, containerPort: 8080}]
          envFrom: [{configMapRef: {name: {{ include "linkly.fullname" . }}}}]
          env:
            - name: DATABASE_URL
              valueFrom: {secretKeyRef: {name: {{ .Values.database.existingSecret }}, key: url}}
          readinessProbe: {httpGet: {path: /readyz, port: http}, periodSeconds: 5}
          livenessProbe: {httpGet: {path: /healthz, port: http}, periodSeconds: 10}
          resources: {{- toYaml .Values.resources | nindent 12 }}
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities: {drop: [ALL]}
EOF
cat > templates/service.yaml <<'EOF'
apiVersion: v1
kind: Service
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
spec:
  selector: {{- include "linkly.selectorLabels" . | nindent 4 }}
  ports: [{name: http, port: {{ .Values.service.port }}, targetPort: http}]
EOF
cat > templates/httproute.yaml <<'EOF'
{{- if and .Values.httpRoute.enabled .Values.ingress.enabled }}
{{- fail "enable either httpRoute or ingress, not both" }}
{{- end }}
{{- if .Values.httpRoute.enabled }}
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
spec:
  parentRefs: {{- toYaml .Values.httpRoute.parentRefs | nindent 4 }}
  hostnames: {{- toYaml .Values.httpRoute.hostnames | nindent 4 }}
  rules:
    - backendRefs: [{name: {{ include "linkly.fullname" . }}, port: {{ .Values.service.port }}}]
{{- end }}
EOF
cat > templates/ingress.yaml <<'EOF'
{{- if .Values.ingress.enabled }}
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
spec:
  ingressClassName: {{ required "ingress.className is required (e.g. traefik, haproxy)" .Values.ingress.className }}
  {{- with .Values.ingress.tlsSecret }}
  tls: [{hosts: [{{ $.Values.ingress.host | quote }}], secretName: {{ . }}}]
  {{- end }}
  rules:
    - host: {{ .Values.ingress.host | quote }}
      http:
        paths:
          - path: /
            pathType: Prefix
            backend: {service: {name: {{ include "linkly.fullname" . }}, port: {name: http}}}
{{- end }}
EOF
cat > templates/hpa.yaml <<'EOF'
{{- if .Values.autoscaling.enabled }}
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
spec:
  scaleTargetRef: {apiVersion: apps/v1, kind: Deployment, name: {{ include "linkly.fullname" . }}}
  minReplicas: {{ .Values.autoscaling.minReplicas }}
  maxReplicas: {{ .Values.autoscaling.maxReplicas }}
  metrics:
    - type: Resource
      resource: {name: cpu, target: {type: Utilization, averageUtilization: {{ .Values.autoscaling.targetCPUUtilizationPercentage }}}}
{{- end }}
EOF
cat > templates/tests/test-readyz.yaml <<'EOF'
apiVersion: v1
kind: Pod
metadata:
  name: {{ include "linkly.fullname" . }}-test-readyz
  annotations: {helm.sh/hook: test, helm.sh/hook-delete-policy: before-hook-creation}
spec:
  restartPolicy: Never
  securityContext: {runAsNonRoot: true, runAsUser: 65532}
  containers:
    - name: curl
      image: curlimages/curl:8.17.0
      args: ["--fail", "--silent", "--max-time", "5", "http://{{ include "linkly.fullname" . }}:{{ .Values.service.port }}/readyz"]
EOF
cat > templates/NOTES.txt <<'EOF'
linkly {{ .Chart.AppVersion }} is installed as "{{ .Release.Name }}" in {{ .Release.Namespace }}.
{{- if .Values.httpRoute.enabled }}
URL: https://{{ first .Values.httpRoute.hostnames }}/
{{- end }}
EOF
cd ../..
echo "== lint"
helm lint chart/linkly --strict --quiet && echo "lint: ok"
echo "== render and validate: defaults, autoscaling, ingress instead of a route"
helm template linkly chart/linkly | kubeconform -strict -summary
helm template linkly chart/linkly --set autoscaling.enabled=true | kubeconform -strict -summary
helm template linkly chart/linkly --set httpRoute.enabled=false --set ingress.enabled=true \
  --set ingress.className=traefik | kubeconform -strict -summary
echo "== guard rails"
helm template linkly chart/linkly --set ingress.enabled=true --set ingress.className=traefik 2>&1 | head -1
helm template linkly chart/linkly --set httpRoute.enabled=false --set ingress.enabled=true 2>&1 | head -1
helm template linkly chart/linkly --set config.logLevel=verbose --set replicaCount=0 2>&1 | grep '^- at' | sort
echo "== package and publish 1.0.0 (app 1.4.1)"
helm package chart/linkly --version 1.0.0 --app-version 1.4.1 -d dist
helm push dist/linkly-1.0.0.tgz oci://localhost:5000/charts --plain-http 2>&1 | head -1

# ---------- Part 2: the environments ----------
mkdir -p deploy/overlays/staging deploy/overlays/production deploy/components/zone-spread && cd deploy
helm pull oci://localhost:5000/charts/linkly --version 1.0.0 --plain-http --untar --untardir charts/linkly-1.0.0 >/dev/null 2>&1
cat > overlays/staging/values.yaml <<'EOF'
replicaCount: 1
image: {tag: "1.5.0-rc.2"}
config: {logLevel: debug, baseUrl: "https://lnk.staging.example.com", redisAddr: "linkly-redis:6379"}
database: {existingSecret: linkly-db-staging}
httpRoute: {hostnames: [lnk.staging.example.com]}
EOF
cat > overlays/staging/kustomization.yaml <<'EOF'
namespace: linkly-staging
helmGlobals: {chartHome: ../../charts}
helmCharts:
  - name: linkly
    repo: oci://localhost:5000/charts
    version: 1.0.0
    releaseName: linkly
    namespace: linkly-staging
    valuesFile: values.yaml
    skipTests: true
labels:
  - pairs: {env: staging}
EOF
cat > overlays/production/values.yaml <<'EOF'
config: {logLevel: info, baseUrl: "https://lnk.example.com", redisAddr: "redis.linkly-prod.svc:6379"}
database: {existingSecret: linkly-db-prod}
httpRoute: {hostnames: [lnk.example.com, go.example.com]}
autoscaling: {enabled: true, minReplicas: 3, maxReplicas: 20}
resources:
  requests: {cpu: 250m, memory: 128Mi}
  limits: {memory: 256Mi}
EOF
cat > components/zone-spread/kustomization.yaml <<'EOF'
apiVersion: kustomize.config.k8s.io/v1alpha1
kind: Component
patches:
  - target: {kind: Deployment, name: linkly}
    patch: |-
      - op: add
        path: /spec/template/spec/topologySpreadConstraints
        value:
          - maxSkew: 1
            topologyKey: topology.kubernetes.io/zone
            whenUnsatisfiable: ScheduleAnyway
            labelSelector: {matchLabels: {app.kubernetes.io/instance: linkly}}
EOF
cat > overlays/production/kustomization.yaml <<'EOF'
namespace: linkly-prod
helmGlobals: {chartHome: ../../charts}
helmCharts:
  - name: linkly
    repo: oci://localhost:5000/charts
    version: 1.0.0
    releaseName: linkly
    namespace: linkly-prod
    valuesFile: values.yaml
    skipTests: true
components: [../../components/zone-spread]
labels:
  - pairs: {env: production}
EOF
for env in staging production; do
  echo "== $env"
  kustomize build --enable-helm overlays/$env > $env.yaml
  yq -N '.kind + "/" + .metadata.name' $env.yaml | paste -sd' '
  kubeconform -strict -summary $env.yaml
done
echo "== what differs (Deployment and route)"
for env in staging production; do
  yq -o json -I0 'select(.kind == "Deployment") | {"replicas": .spec.replicas, "image": .spec.template.spec.containers[0].image,
    "limits": .spec.template.spec.containers[0].resources.limits, "spread": (.spec.template.spec.topologySpreadConstraints | length)}' $env.yaml
  yq -o json -I0 'select(.kind == "HTTPRoute") | .spec.hostnames' $env.yaml
done
== lint
lint: ok
== render and validate: defaults, autoscaling, ingress instead of a route
Summary: 5 resources found parsing stdin - Valid: 5, Invalid: 0, Errors: 0, Skipped: 0
Summary: 6 resources found parsing stdin - Valid: 6, Invalid: 0, Errors: 0, Skipped: 0
Summary: 5 resources found parsing stdin - Valid: 5, Invalid: 0, Errors: 0, Skipped: 0
== guard rails
Error: execution error at (linkly/templates/httproute.yaml:2:4): enable either httpRoute or ingress, not both
Error: execution error at (linkly/templates/ingress.yaml:8:23): ingress.className is required (e.g. traefik, haproxy)
- at '/config/logLevel': value must be one of 'debug', 'info', 'warn', 'error'
- at '/replicaCount': minimum: got 0, want 1
== package and publish 1.0.0 (app 1.4.1)
Successfully packaged chart and saved it to: dist/linkly-1.0.0.tgz
Pushed: localhost:5000/charts/linkly:1.0.0
== staging
ConfigMap/linkly Service/linkly Deployment/linkly HTTPRoute/linkly
Summary: 4 resources found in 1 file - Valid: 4, Invalid: 0, Errors: 0, Skipped: 0
== production
ConfigMap/linkly Service/linkly Deployment/linkly HorizontalPodAutoscaler/linkly HTTPRoute/linkly
Summary: 5 resources found in 1 file - Valid: 5, Invalid: 0, Errors: 0, Skipped: 0
== what differs (Deployment and route)
{"replicas":1,"image":"ghcr.io/acme/linkly:1.5.0-rc.2","limits":{"memory":"128Mi"},"spread":0}
["lnk.staging.example.com"]
{"replicas":null,"image":"ghcr.io/acme/linkly:1.4.1","limits":{"memory":"256Mi"},"spread":1}
["lnk.example.com","go.example.com"]

Walkthrough

Part 1: the chart

  • Values are the interface. Only what environments really change is exposed: image, config, database Secret name, routing, autoscaling, resources, pod annotations. Everything else (ports, probes, security context) is fixed in the templates, because changing it is a chart change, not a deployment choice.
  • The schema (values.schema.json) rejects unknown top-level keys, bad log levels and a zero replica count; the guard-rail output shows two violations reported at once. podAnnotations accepts any key but only string values.
  • Routing. httpRoute.enabled is the default. On a cluster without Gateway API, set httpRoute.enabled=false, ingress.enabled=true and a className for a maintained controller (Traefik, HAProxy, a cloud load balancer controller); the required call stops an Ingress without a class, and fail stops both being enabled at once. The community ingress-nginx controller is retired, so it isn't the example here.
  • Autoscaling. When autoscaling.enabled is true, the HPA appears and the Deployment omits replicas, so helm upgrade or a GitOps sync never resets what the HPA decided.
  • Rollouts on config change come from the checksum/config annotation (Files, ConfigMaps & Secrets); selectors use only the two stable labels (Field Notes).
  • Versioning. Chart.yaml holds 0.0.0-dev; the release step stamps --version 1.0.0 --app-version 1.4.1, exactly as a CI job would from a Git tag (Chart Versioning).

Part 2: the environments

  • The deployment repository vendors the published chart with helm pull into charts/linkly-1.0.0/ (Kustomize would pull it itself from an HTTPS registry; this registry is plain HTTP). Both overlays render the same immutable chart version: promotion means changing version: in an overlay.
  • Each overlay has its own values.yaml with only what differs. Staging runs a release candidate with debug logs and one replica; production turns on autoscaling, raises resources and serves two hostnames.
  • The zone-spread component adds a topology spread constraint the chart doesn't expose, without forking it. Only production includes it, which the "spread" count in the output confirms.
  • skipTests: true keeps the chart's test Pod out of the rendered manifests (Helm Rendered Through Kustomize), and labels tags every object with its environment.
  • Every overlay's output is validated with kubeconform -strict, Gateway API schemas included, and the summary of differences is what a reviewer reads in a pull request.

Deploying it (sample)

On a real cluster, with the database Secrets created by your secret manager, either apply the rendered output directly:

bash
kustomize build --enable-helm deploy/overlays/staging | kubectl apply --server-side -f -

or point a GitOps controller at deploy/overlays/production with Helm support in Kustomize enabled (Argo CD: kustomize.buildOptions: --enable-helm in argocd-cm). The planned GitOps course turns this repository into a promotion pipeline from staging to production.

Extensions

  1. Add a components/monitoring with a Prometheus Operator ServiceMonitor for /metrics, and validate it with kubeconform (its schema is in the image).
  2. Add a PodDisruptionBudget to the chart behind podDisruptionBudget.enabled, with a schema entry, and enable it in production only.
  3. Publish 1.0.1 with a template fix and promote it to staging only; show the diff between the two overlays' output.
  4. Write the CI script from Rendering & Validating in CI for this repository: lint with each overlay's values, build both overlays, validate, and fail on stale rendered files.
  5. Replace the vendored chart with a helm install of the same chart and values, plus a post-renderer plugin for the zone spread, and compare what each approach gives you (releases, hooks, helm test).

Test yourself

Why does the Deployment template omit replicas when autoscaling is enabled?

  1. HPAs require it
  2. So applying the manifests never resets the replica count the HPA chose
  3. To save space
  4. Kubernetes forbids both

How is linkly promoted from staging to production in this layout?

  1. Copy files between branches
  2. Change the chart version (and values) in the production overlay through a reviewed commit
  3. Run helm upgrade by hand
  4. Retag the image

Production needs a field the chart doesn't expose. What did the project use?

  1. A fork of the chart
  2. kubectl patch after deploy
  3. A Kustomize component with a JSON patch
  4. A new values key in production only