Skip to content
CNPE · Chapter 9 of 22 Day 7: Platform APIs – a resource of your own

Day 7: Platform APIs – a resource of your own

Goal: Design a CustomResourceDefinition Umgebung that teams use to order environments: a schema with required fields, defaults, limits and a CEL rule, custom columns, a status part, rights for the teams and a second API version · Duration: approx. 60 min · Prerequisite: Day 6

Briefing

  • A platform offers teams APIs instead of tickets. Instead of “please set up a test environment for me”, the team writes an object kind: Umgebung – with kubectl, via GitOps, from a portal.
  • Kubernetes can be extended with resource types of your own: a CustomResourceDefinition (CRD) introduces a new type to the API server. It stores, validates and versions it like any other. It does not do anything – for that you need a controller (Crossplane, Day 8).
  • What makes a good platform API is today’s topic: a tight schema that rejects errors at creation time instead of hours later, sensible defaults, readable output and a clean path to the next version.
CRD building block What for
openAPIV3Schema Types, required fields, enum, minimum/maximum, default
x-kubernetes-validations Rules across several fields (CEL)
additionalPrinterColumns Columns for kubectl get
subresources.status status can only be changed through its own endpoint
versions Several versions, exactly one is stored

Drill 1: The CRD

# on cp1
mkdir -p ~/cnpe/tag07 && cd ~/cnpe/tag07
cat > crd-umgebung.yaml <<'EOF'
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: umgebungen.plattform.lab        # must be named <plural>.<group>
spec:
  group: plattform.lab                  # API group of the platform
  scope: Namespaced                     # objects belong in a team namespace
  names:
    kind: Umgebung
    plural: umgebungen
    singular: umgebung
    shortNames: [umg]                   # kubectl get umg
  versions:
  - name: v1alpha1
    served: true                        # reachable through the API
    storage: true                       # stored in etcd in this version
    subresources:
      status: {}                        # status can only be changed via /status
    additionalPrinterColumns:
    - {name: Team, type: string, jsonPath: .spec.team}
    - {name: Groesse, type: string, jsonPath: .spec.groesse}
    - {name: Ablauf, type: integer, jsonPath: .spec.stunden}
    - {name: Phase, type: string, jsonPath: .status.phase}
    schema:
      openAPIV3Schema:
        type: object
        properties:
          spec:
            type: object
            required: [team]            # no environment without a team
            properties:
              team:
                type: string
                enum: [blue, green]
              groesse:
                type: string
                enum: [S, M, L]
                default: S              # set by the API server if empty
              stunden:
                type: integer
                minimum: 1
                maximum: 168            # at most one week
                default: 24
              datenbank:
                type: boolean
                default: false
            x-kubernetes-validations:   # CEL rule across two fields
            - rule: "self.groesse != 'L' || self.stunden <= 24"
              message: "Groesse L nur fuer hoechstens 24 Stunden"
          status:
            type: object
            properties:
              phase:
                type: string
EOF
k apply -f crd-umgebung.yaml
# wait until the API server offers the type
k wait --for=condition=Established crd/umgebungen.plattform.lab
k api-resources --api-group=plattform.lab
k explain umgebung.spec

Expected (abridged):

customresourcedefinition.apiextensions.k8s.io/umgebungen.plattform.lab created
customresourcedefinition.apiextensions.k8s.io/umgebungen.plattform.lab condition met
NAME         SHORTNAMES   APIVERSION               NAMESPACED   KIND
umgebungen   umg          plattform.lab/v1alpha1   true         Umgebung
GROUP:      plattform.lab
KIND:       Umgebung
VERSION:    v1alpha1

FIELD: spec <Object>
...
FIELDS:
  datenbank <boolean>
  groesse   <string>
  enum: S, M, L
  stunden   <integer>
  team  <string> -required-
  enum: blue, green

k explain works right away – the schema is the documentation. With description: on every field it becomes readable (Enterprise Note).

Save your progress? Sign up for free

Drill 2: Defaults and validation

# on cp1
cat > umgebung-test.yaml <<'EOF'
apiVersion: plattform.lab/v1alpha1
kind: Umgebung
metadata:
  name: feature-login
  namespace: team-blue
spec:
  team: blue                            # only the required field
EOF
k apply -f umgebung-test.yaml
k -n team-blue get umg
# what the API server stored
k -n team-blue get umg feature-login -o jsonpath='{.spec}{"\n"}'

Expected:

umgebung.plattform.lab/feature-login created
NAME            TEAM   GROESSE   ABLAUF   PHASE
feature-login   blue   S         24
{"datenbank":false,"groesse":"S","stunden":24,"team":"blue"}

The defaults are in the stored object – whoever reads it later sees what applies. Now two invalid orders:

# on cp1
# three errors at once: unknown team, unknown size, too long
printf 'apiVersion: plattform.lab/v1alpha1\nkind: Umgebung\nmetadata:\n  name: kaputt\n  namespace: team-blue\nspec:\n  team: red\n  groesse: XL\n  stunden: 500\n' \
  | k apply -f -
# each field valid on its own, but not together
printf 'apiVersion: plattform.lab/v1alpha1\nkind: Umgebung\nmetadata:\n  name: gross\n  namespace: team-blue\nspec:\n  team: blue\n  groesse: L\n  stunden: 48\n' \
  | k apply -f -

Expected:

The Umgebung "kaputt" is invalid:
* spec.stunden: Invalid value: 500: spec.stunden in body should be less than or equal to 168
* spec.team: Unsupported value: "red": supported values: "blue", "green"
* spec.groesse: Unsupported value: "XL": supported values: "S", "M", "L"
* <nil>: Invalid value: null: some validation rules were not checked because the object was invalid; correct the existing errors to complete validation
The Umgebung "gross" is invalid: spec: Invalid value: Groesse L nur fuer hoechstens 24 Stunden

The CEL rule only runs once the simple checks have passed – hence the last line on the first attempt.

Save your progress? Sign up for free

Drill 3: The status belongs to the controller

spec is the team’s wish, status the platform’s answer. With subresources.status, a normal update ignores the status; it can only be changed through the /status endpoint.

# on cp1
# as the platform (administrator): set the status
#   --subresource=status   write to /status instead of to the object
k -n team-blue patch umg feature-login --subresource=status --type=merge -p '{"status":{"phase":"Bereit"}}'
k -n team-blue get umg
# the same patch without --subresource: silently ignored
k -n team-blue patch umg feature-login --type=merge -p '{"status":{"phase":"Gehackt"}}'
k -n team-blue get umg feature-login -o jsonpath='{.status.phase}{"\n"}'

Expected:

umgebung.plattform.lab/feature-login patched
NAME            TEAM   GROESSE   ABLAUF   PHASE
feature-login   blue   S         24       Bereit
umgebung.plattform.lab/feature-login patched (no change)
Bereit

Save your progress? Sign up for free

Drill 4: Rights for the teams

Anna has edit in team-blue (Day 1). Is she allowed to order environments?

# on cp1
k auth can-i create umgebungen.plattform.lab -n team-blue --as=anna --as-group=team-blue-devs

Expected:

no

The built-in roles do not know custom types. Instead of binding a new role for every team, you extend edit, admin and view via aggregation: a ClusterRole with a specific label is automatically merged into the big role.

# on cp1
cat > rolle-umgebung.yaml <<'EOF'
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: plattform-umgebungen-edit
  labels:                                           # merge into edit and admin
    rbac.authorization.k8s.io/aggregate-to-edit: "true"
    rbac.authorization.k8s.io/aggregate-to-admin: "true"
rules:
- apiGroups: [plattform.lab]
  resources: [umgebungen]                           # not umgebungen/status
  verbs: [get, list, watch, create, update, patch, delete]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: plattform-umgebungen-view
  labels:
    rbac.authorization.k8s.io/aggregate-to-view: "true"
rules:
- apiGroups: [plattform.lab]
  resources: [umgebungen]
  verbs: [get, list, watch]
EOF
k apply -f rolle-umgebung.yaml
k auth can-i create umgebungen.plattform.lab -n team-blue --as=anna --as-group=team-blue-devs
# Change the status? Use --subresource, don't append "…/status" to the name
k auth can-i patch umgebungen.plattform.lab --subresource=status -n team-blue --as=anna --as-group=team-blue-devs
k auth can-i create umgebungen.plattform.lab -n team-green --as=anna --as-group=team-blue-devs
k --context anna get umg

Expected:

clusterrole.rbac.authorization.k8s.io/plattform-umgebungen-edit created
clusterrole.rbac.authorization.k8s.io/plattform-umgebungen-view created
yes
no
no
NAME            TEAM   GROESSE   ABLAUF   PHASE
feature-login   blue   S         24       Bereit

A trap when checking: k auth can-i patch umgebungen.plattform.lab/status answers yes – kubectl reads /status as the object name “status”, not as a subresource. The correct form is --subresource=status.

Save your progress? Sign up for free

Drill 5: The next version

The API matures: v1beta1 is to become the stored version, v1alpha1 stays reachable for now but warns. Both have the same schema – then no conversion webhook is needed.

# on cp1
# extract v1alpha1 as a template for v1beta1
yq '.spec.versions[0].name = "v1beta1"' crd-umgebung.yaml | yq '.spec.versions[0]' > /tmp/v1beta1.yaml
# v1alpha1: no longer stored, marked as deprecated
yq -i '.spec.versions[0].storage = false | .spec.versions[0].deprecated = true |
  .spec.versions[0].deprecationWarning = "plattform.lab/v1alpha1 Umgebung ist veraltet, nutze v1beta1"' crd-umgebung.yaml
# append v1beta1
yq -i '.spec.versions += [load("/tmp/v1beta1.yaml")]' crd-umgebung.yaml
yq '.spec.versions[] | [.name, .served, .storage, .deprecated] | @csv' crd-umgebung.yaml
k apply -f crd-umgebung.yaml
# which versions are in etcd?
k get crd umgebungen.plattform.lab -o jsonpath='{.status.storedVersions}{"\n"}'
k -n team-blue get umg feature-login -o jsonpath='{.apiVersion}{"\n"}'

Expected:

v1alpha1,true,false,true
v1beta1,true,true,null
customresourcedefinition.apiextensions.k8s.io/umgebungen.plattform.lab configured
["v1alpha1","v1beta1"]
Warning: plattform.lab/v1alpha1 Umgebung ist veraltet, nutze v1beta1
plattform.lab/v1alpha1

kubectl still asks for v1alpha1 – it caches the server’s API list for a few hours in ~/.kube/cache/discovery. After a change to CRDs: delete the cache.

# on cp1
rm -rf ~/.kube/cache/discovery
k -n team-blue get umg feature-login -o jsonpath='{.apiVersion}{"\n"}'
k api-resources --api-group=plattform.lab

Expected:

plattform.lab/v1beta1
NAME         SHORTNAMES   APIVERSION              NAMESPACED   KIND
umgebungen   umg          plattform.lab/v1beta1   true         Umgebung

storedVersions shows both versions: old objects are still stored in etcd as v1alpha1. Before you may remove v1alpha1 some day, all objects must have been rewritten (storage migration):

# on cp1
# write every object back once, unchanged – the server stores it in v1beta1
k get umg -A -o json | k replace -f - >/dev/null && echo neu geschrieben
# only then clean up the list in the CRD
k patch crd umgebungen.plattform.lab --subresource=status --type=merge \
  -p '{"status":{"storedVersions":["v1beta1"]}}'
k get crd umgebungen.plattform.lab -o jsonpath='{.status.storedVersions}{"\n"}'

Expected:

neu geschrieben
customresourcedefinition.apiextensions.k8s.io/umgebungen.plattform.lab patched
["v1beta1"]

Save your progress? Sign up for free

Exercise: A new field

Time limit: 5 minutes. Teams want to give an environment a zweck (purpose; text, at most 60 characters). Add the field to v1beta1 and create an environment with a purpose.

Solution

# on cp1
cd ~/cnpe/tag07
# add the field only in v1beta1 (index 1)
yq -i '.spec.versions[1].schema.openAPIV3Schema.properties.spec.properties.zweck = {"type":"string","maxLength":60}' crd-umgebung.yaml
k apply -f crd-umgebung.yaml
printf 'apiVersion: plattform.lab/v1beta1\nkind: Umgebung\nmetadata:\n  name: lasttest\n  namespace: team-blue\nspec:\n  team: blue\n  zweck: Lasttest vor dem Release\n' | k apply -f -
k -n team-blue get umg lasttest -o jsonpath='{.spec.zweck}{"\n"}'

Expected:

customresourcedefinition.apiextensions.k8s.io/umgebungen.plattform.lab configured
umgebung.plattform.lab/lasttest created
Lasttest vor dem Release

A new, optional field is a compatible change – no new version needed. Renaming fields or adding required fields, on the other hand, does need one.

Save your progress? Sign up for free

Challenge

Time limit: 10 minutes. A colleague creates an object with a typo: stundne: 4. With kubectl he gets an error right away. His script, which calls the API without field validation, does create the object, though. What ends up in spec, and why?

Solution

# on cp1
# like kubectl by default: strict field validation
printf 'apiVersion: plattform.lab/v1beta1\nkind: Umgebung\nmetadata:\n  name: tippfehler\n  namespace: team-blue\nspec:\n  team: blue\n  stundne: 4\n' \
  | k apply -f -
# like a client without field validation
printf 'apiVersion: plattform.lab/v1beta1\nkind: Umgebung\nmetadata:\n  name: tippfehler\n  namespace: team-blue\nspec:\n  team: blue\n  stundne: 4\n' \
  | k apply --validate=false -f -
k -n team-blue get umg tippfehler -o jsonpath='{.spec}{"\n"}'
k -n team-blue delete umg tippfehler

Expected:

Error from server (BadRequest): error when creating "STDIN": Umgebung in version "v1beta1" cannot be handled as a Umgebung: strict decoding error: unknown field "spec.stundne"
umgebung.plattform.lab/tippfehler created
{"datenbank":false,"groesse":"S","stunden":24,"team":"blue"}
umgebung.plattform.lab "tippfehler" deleted from team-blue namespace

Since version 1.27, kubectl sends fieldValidation=Strict – the server rejects unknown fields. Without this parameter, the server silently removes unknown fields (pruning), and the default stunden: 24 applies. The object looks valid but does not do what was intended. So always use strict field validation in your own tools and pipelines.

Save your progress? Sign up for free

Checkpoint

# on cp1
# stored version is only v1beta1 now
k get crd umgebungen.plattform.lab -o jsonpath='{.status.storedVersions}{"\n"}'
# two environments in team-blue
k -n team-blue get umg -o name
# Anna may order, but may not set a status
k auth can-i create umgebungen.plattform.lab -n team-blue --as=anna --as-group=team-blue-devs
k auth can-i patch umgebungen.plattform.lab --subresource=status -n team-blue --as=anna --as-group=team-blue-devs

Expected:

["v1beta1"]
umgebung.plattform.lab/feature-login
umgebung.plattform.lab/lasttest
yes
no

Interview Note

  • CRD or ConfigMap for platform configuration? The CRD brings a schema, validation, RBAC per type, custom columns and versions. A ConfigMap is untyped text.
  • Why status as a subresource? Separation of responsibility: teams write spec, only the controller writes status. Rights can be granted separately.
  • How do you safely remove an old API version? Have the new version stored, rewrite all objects, clean up storedVersions, then served: false, and finally remove it.

Enterprise Note

  • Every field with a description: – that is the documentation teams see with kubectl explain and in portals.
  • Different schemas between versions need a conversion webhook; it is better to keep versions compatible for as long as possible.
  • CRDs belong to the platform: roll them out via GitOps and grant teams access only to the objects, never to the CRD itself.
  • Large-scale storage migration is handled by the StorageVersionMigrator instead of get | replace.

Contents

More