TExcelTAD
Home › Kubernetes Packaging: Helm & Kustomize › Helm & Kustomize Exercises

Helm & Kustomize Exercises

The first four exercises re-implement, as small pure functions, the rules Helm and Kustomize apply: merging values, choosing a chart version, merging lists by key, and applying a JSON patch. The calls are already in place. Run the starter first: it prints placeholder answers, which shows what the calls expect. Complete the code marked TODO until the output matches the expected output, then compare with the solution. The last two exercises are real tool sessions with a bug to fix.

Exercise 1: Merge values like Helm

Topics: Values Files & Overrides

Write merge(base, override): maps merge recursively, any other value (including lists) in override replaces the base value, and a None (YAML null) in override deletes the key. Neither input may be modified.

python · try it yourself
def merge(base, override):
    # TODO: deep-merge maps, replace everything else, delete keys set to None
    return base

chart = {"replicaCount": 2, "image": {"repository": "ghcr.io/acme/linkly", "tag": "1.4.0"},
         "hostnames": ["lnk.example.com"], "resources": {"limits": {"cpu": "500m", "memory": "128Mi"}}}
prod = {"replicaCount": 5, "image": {"tag": "1.4.1"}, "hostnames": ["go.example.com"],
        "resources": {"limits": {"cpu": None}}}
print(merge(chart, prod))
print(chart["image"]["tag"])
{'replicaCount': 2, 'image': {'repository': 'ghcr.io/acme/linkly', 'tag': '1.4.0'}, 'hostnames': ['lnk.example.com'], 'resources': {'limits': {'cpu': '500m', 'memory': '128Mi'}}}
1.4.0

Expected output:

text
{'replicaCount': 5, 'image': {'repository': 'ghcr.io/acme/linkly', 'tag': '1.4.1'}, 'hostnames': ['go.example.com'], 'resources': {'limits': {'memory': '128Mi'}}}
1.4.0
Show solution
python
def merge(base, override):
    out = dict(base)
    for key, value in override.items():
        if value is None:
            out.pop(key, None)
        elif isinstance(value, dict) and isinstance(out.get(key), dict):
            out[key] = merge(out[key], value)
        else:
            out[key] = value
    return out

dict(base) copies the top level, and every nested map that changes is rebuilt by the recursive call, so chart is never modified.

Exercise 2: Pick a chart version

Topics: Chart Versioning

Write pick(versions, constraint) for constraints X.Y.Z (exact), ~X.Y.Z (same major and minor) and ^X.Y.Z (same major; for ^0.Y.Z, same minor). Return the highest matching version, or None. Pre-releases (1.2.0-rc.1) never match. Compare versions numerically, not as strings.

python · try it yourself
def pick(versions, constraint):
    # TODO: parse the constraint, filter the versions, return the highest
    return versions[0]

available = ["0.9.3", "0.10.0", "1.0.0", "1.1.0", "1.1.10", "1.1.9", "1.2.0-rc.1", "1.10.0", "2.0.0"]
for c in ["1.1.0", "~1.1.0", "^1.0.0", "^0.9.0", "~3.0.0"]:
    print(f"{c:7} -> {pick(available, c)}")
1.1.0   -> 0.9.3
~1.1.0  -> 0.9.3
^1.0.0  -> 0.9.3
^0.9.0  -> 0.9.3
~3.0.0  -> 0.9.3

Expected output:

text
1.1.0   -> 1.1.0
~1.1.0  -> 1.1.10
^1.0.0  -> 1.10.0
^0.9.0  -> 0.9.3
~3.0.0  -> None
Show solution
python
def pick(versions, constraint):
    op = constraint[0] if constraint[0] in "~^" else "="
    lo = tuple(int(x) for x in constraint.lstrip("~^").split("."))
    if op == "=":
        hi = lo[:2] + (lo[2] + 1,)
    elif op == "~":
        hi = (lo[0], lo[1] + 1, 0)
    else:
        hi = (lo[0] + 1, 0, 0) if lo[0] > 0 else (0, lo[1] + 1, 0)
    ok = [tuple(int(x) for x in v.split(".")) for v in versions if "-" not in v]
    ok = [v for v in ok if lo <= v < hi]
    return ".".join(map(str, max(ok))) if ok else None

Tuples of integers compare element by element, so (1, 1, 10) > (1, 1, 9), while the strings compare the other way.

Exercise 3: Merge a list by key

Topics: Strategic-Merge & JSON Patches

A strategic merge patch merges lists like env by their name. Write merge_by_key(base, patch, key): entries whose key exists in the base are updated in place (field by field), new entries are appended after the base entries in patch order, and an entry with "$patch": "delete" removes the matching base entry.

python · try it yourself
def merge_by_key(base, patch, key="name"):
    # TODO: update matching entries, append new ones, honour "$patch": "delete"
    return base

base_env = [{"name": "LOG_LEVEL", "value": "info"},
            {"name": "REDIS_ADDR", "value": "linkly-redis:6379"},
            {"name": "DEBUG_TOKEN", "value": "dev"}]
patch_env = [{"name": "LOG_LEVEL", "value": "warn"},
             {"name": "GOMEMLIMIT", "value": "200MiB"},
             {"name": "DEBUG_TOKEN", "$patch": "delete"}]
for entry in merge_by_key(base_env, patch_env):
    print(entry)
{'name': 'LOG_LEVEL', 'value': 'info'}
{'name': 'REDIS_ADDR', 'value': 'linkly-redis:6379'}
{'name': 'DEBUG_TOKEN', 'value': 'dev'}

Expected output:

text
{'name': 'LOG_LEVEL', 'value': 'warn'}
{'name': 'REDIS_ADDR', 'value': 'linkly-redis:6379'}
{'name': 'GOMEMLIMIT', 'value': '200MiB'}
Show solution
python
def merge_by_key(base, patch, key="name"):
    out = [dict(e) for e in base]
    for p in patch:
        match = next((e for e in out if e[key] == p[key]), None)
        if p.get("$patch") == "delete":
            if match is not None:
                out.remove(match)
        elif match is not None:
            match.update(p)
        else:
            out.append(dict(p))
    return out

(Kustomize's real output may order merged entries slightly differently; the rule "matched by key, not by position" is what matters.)

Exercise 4: Apply a JSON patch

Topics: Strategic-Merge & JSON Patches

Write apply(doc, ops) for the operations add, replace and remove on JSON Pointer paths: segments are separated by /, ~1 means / and ~0 means ~, list indexes are numbers, and - as the last segment of an add appends to a list. add on a list index inserts before it.

python · try it yourself
import copy

def apply(doc, ops):
    doc = copy.deepcopy(doc)
    # TODO: walk to the parent of each path, then add/replace/remove
    return doc

route = {"metadata": {"name": "linkly", "annotations": {}},
         "spec": {"hostnames": ["lnk.example.com"], "rules": [{"backend": "linkly"}]}}
ops = [
    {"op": "add", "path": "/metadata/annotations/acme.example.com~1owner", "value": "links"},
    {"op": "add", "path": "/spec/hostnames/-", "value": "go.example.com"},
    {"op": "add", "path": "/spec/rules/0", "value": {"path": "/admin", "backend": "linkly-admin"}},
    {"op": "replace", "path": "/metadata/name", "value": "linkly-prod"},
    {"op": "remove", "path": "/spec/rules/1/backend"},
]
print(apply(route, ops))
{'metadata': {'name': 'linkly', 'annotations': {}}, 'spec': {'hostnames': ['lnk.example.com'], 'rules': [{'backend': 'linkly'}]}}

Expected output:

text
{'metadata': {'name': 'linkly-prod', 'annotations': {'acme.example.com/owner': 'links'}}, 'spec': {'hostnames': ['lnk.example.com', 'go.example.com'], 'rules': [{'path': '/admin', 'backend': 'linkly-admin'}, {}]}}
Show solution
python
def apply(doc, ops):
    doc = copy.deepcopy(doc)
    for op in ops:
        parts = [p.replace("~1", "/").replace("~0", "~") for p in op["path"].split("/")[1:]]
        parent = doc
        for p in parts[:-1]:
            parent = parent[int(p)] if isinstance(parent, list) else parent[p]
        last = parts[-1]
        if isinstance(parent, list):
            if op["op"] == "add":
                parent.insert(len(parent) if last == "-" else int(last), op["value"])
            elif op["op"] == "replace":
                parent[int(last)] = op["value"]
            else:
                del parent[int(last)]
        else:
            if op["op"] == "remove":
                del parent[last]
            else:
                parent[last] = op["value"]
    return doc

Note that the last operation's index 1 refers to the list after the insert at index 0: operations apply in order, each to the result of the previous one.

Exercise 5: Fix the chart

Topics: Templates & Pipelines, Flow Control & Scope, Validating with kubeconform

This chart has three bugs. The session shows what CI reports. Find and fix them so that both commands succeed for the default values and with --set autoscaling.enabled=true, and kubeconform reports Valid: 2 (Deployment and Service) and Valid: 3 (plus the HPA).

bash · try it yourself
mkdir -p linkly/templates && cd linkly
printf 'apiVersion: v2\nname: linkly\nversion: 1.0.0\nappVersion: "1.4.0"\n' > Chart.yaml
cat > values.yaml <<'EOF'
replicaCount: 2
autoscaling: {enabled: false, minReplicas: 2, maxReplicas: 10}
podLabels:
  canary: "false"
EOF
cat > templates/deployment.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ .Release.Name }}
spec:
  replicas: {{ .Values.replicaCount }}
  selector: {matchLabels: {app: linkly}}
  template:
    metadata:
      labels:
        app: linkly
        {{- range $k, $v := .Values.podLabels }}
        {{ $k }}: {{ $v }}
        {{- end }}
    spec:
      containers:
        - name: linkly
          image: ghcr.io/acme/linkly:{{ .Chart.AppVersion }}
EOF
cat > templates/service.yaml <<'EOF'
apiVersion: v1
kind: Service
metadata:
  name: {{ .Release.Name }}
spec:
  selector: {app: linkly}
  ports: [{port: 80, targetPort: 8080}]
EOF
cat > templates/hpa.yaml <<'EOF'
{{- if .Values.autoscaling.enabled }}
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: {{ .Release.Name }}
spec:
  scaleTargetRef: {apiVersion: apps/v1, kind: Deployment, name: {{ .Release.Name }}}
  minReplicas: {{ .Values.autoscaling.minReplicas }}
  maxReplicas: {{ .Values.autoscaling.max }}
{{- end }}
EOF
helm template web . | kubeconform -n 1 -strict -summary 2>&1 | sed -E 's/problem validating schema.*json#.//'
helm template web . --set autoscaling.enabled=true | kubeconform -n 1 -strict -summary 2>&1 | sed -E 's/problem validating schema.*json#.//'
stdin - Deployment web is invalid:  - at '/spec/template/metadata/labels/canary': got boolean, want null or string
Summary: 2 resources found parsing stdin - Valid: 1, Invalid: 1, Errors: 0, Skipped: 0
stdin - Deployment web is invalid:  - at '/spec/template/metadata/labels/canary': got boolean, want null or string
stdin - HorizontalPodAutoscaler web is invalid:  - at '/spec/maxReplicas': got null, want integer
Summary: 3 resources found parsing stdin - Valid: 1, Invalid: 2, Errors: 0, Skipped: 0
Show solution
  1. The label value false was inserted unquoted, so it became a YAML boolean, and label values must be strings: use {{ $k }}: {{ $v | quote }}.
  2. The HPA reads .Values.autoscaling.max, a key that doesn't exist, so it rendered maxReplicas: with no value (null), and kubeconform reported got null, want integer once autoscaling was on. Use .Values.autoscaling.maxReplicas. A values schema can't catch a template reading the wrong key, but required can: {{ required "autoscaling.maxReplicas is required" .Values.autoscaling.maxReplicas }}.
  3. With autoscaling on, the Deployment still sets replicas, so every upgrade fights the HPA. kubeconform can't see this one: it's a logic bug. Wrap the field: {{- if not .Values.autoscaling.enabled }} / replicas: … / {{- end }}.
bash
helm template web . | kubeconform -strict -summary
# Summary: 2 resources found parsing stdin - Valid: 2, Invalid: 0, Errors: 0, Skipped: 0
helm template web . --set autoscaling.enabled=true | kubeconform -strict -summary
# Summary: 3 resources found parsing stdin - Valid: 3, Invalid: 0, Errors: 0, Skipped: 0

Exercise 6: Fix the overlay

Topics: Bases & Overlays, ConfigMap & Secret Generators, Field Notes

The production overlay should run linkly with LOG_LEVEL=warn, keep REDIS_ADDR from the base, and give the container a 256Mi memory limit. The output shows what it actually produces: the build succeeds, yet two of the three requirements are missed. Fix the overlay's kustomization.yaml (not the base).

bash · try it yourself
mkdir -p base prod
cat > base/deployment.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: linkly
spec:
  selector: {matchLabels: {app: linkly}}
  template:
    metadata: {labels: {app: linkly}}
    spec:
      containers:
        - name: linkly
          image: ghcr.io/acme/linkly:1.4.0
          envFrom: [{configMapRef: {name: linkly-config}}]
EOF
cat > base/kustomization.yaml <<'EOF'
resources: [deployment.yaml]
configMapGenerator:
  - name: linkly-config
    literals: [LOG_LEVEL=info, REDIS_ADDR=linkly-redis:6379]
EOF
cat > prod/kustomization.yaml <<'EOF'
resources: [../base]
namespace: linkly-prod
configMapGenerator:
  - name: linkly-config
    behavior: replace
    literals: [LOG_LEVEL=warn]
patches:
  - target: {kind: Deployment, name: linkly-api}
    patch: |-
      - op: add
        path: /spec/template/spec/containers/0/resources
        value: {limits: {memory: 256Mi}}
EOF
kustomize build prod | yq -o json -I0 '{"kind": .kind, "data": .data, "resources": .spec.template.spec.containers[0].resources}'
{"kind":"ConfigMap","data":{"LOG_LEVEL":"warn"},"resources":null}
{"kind":"Deployment","data":null,"resources":null}
Show solution
  1. behavior: replace threw away the base's keys, including REDIS_ADDR; use behavior: merge.
  2. The patch targets linkly-api, but the Deployment is called linkly. A target selector that matches nothing is silently skipped (Field Notes); use name: linkly.
yaml
resources: [../base]
namespace: linkly-prod
configMapGenerator:
  - name: linkly-config
    behavior: merge
    literals: [LOG_LEVEL=warn]
patches:
  - target: {kind: Deployment, name: linkly}
    patch: |-
      - op: add
        path: /spec/template/spec/containers/0/resources
        value: {limits: {memory: 256Mi}}

Test yourself

In Exercise 2, why must versions be compared as integer tuples?

  1. Strings are slower
  2. As strings, '1.10.0' sorts before '1.9.0'
  3. Tuples are required by Helm
  4. To handle pre-releases

In Exercise 6, why did kustomize build succeed although the memory limit was missing?

  1. Limits are optional in Kubernetes
  2. A patch whose target selector matches nothing is skipped without an error
  3. JSON patches can't add maps
  4. behavior: replace removed it