Sub topic 5
Describing your API with a structural schema
This chapter assumes you can read a CRD manifest like the WebApp example from the previous chapter and use kubectl apply. It covers the openAPIV3Schema block: what makes a schema structural, how pruning and defaulting work, and the errors you will hit first.
What "structural" means
Since apiextensions.k8s.io/v1, every CRD schema must be structural. A schema is structural when:
- Every node sets a
type. The exceptions are nodes that setx-kubernetes-int-or-string: trueorx-kubernetes-preserve-unknown-fields: true. - Inside
allOf,anyOf,oneOfandnot, you only add validation. You do not settype,default,descriptionoradditionalPropertiesthere. - Under
metadata, you only describenameandgenerateName.
The API server rejects a CRD that breaks these rules when you apply it. The rules let the server know the shape of every object, which it needs for pruning and defaulting.
Pruning and defaulting
When a request arrives, the API server processes the object in a fixed order.
Pruning silently drops any field the schema does not declare. If you write spec.replica instead of spec.replicas, the typo disappears and you get no error. Defaults are also applied when objects are read from etcd, so adding a default later affects existing objects.
A fuller schema
This fragment goes under versions[].schema.openAPIV3Schema.properties.spec. It adds constraints to the WebApp type.
type: object
required: ["image"]
properties:
image:
type: string
minLength: 1
replicas:
type: integer
minimum: 0
maximum: 50
default: 1
strategy:
type: string
enum: ["RollingUpdate", "Recreate"]
default: RollingUpdate
resources:
type: object
default: {}
properties:
cpu:
type: string
pattern: '^[0-9]+m?$'
default: "100m"The default: {} on resources matters. Defaults for nested fields only apply when the parent object exists. Without default: {}, a resource that omits resources never gets cpu: 100m.
Common errors
- Missing
type: the CRD is rejected with a message such asmust not be empty for specified object fields. - Fields vanish: pruning removed them. Declare them in the schema. For free-form data, set
x-kubernetes-preserve-unknown-fields: trueon that node only. - Default not applied: the parent object is absent and has no default, or the default itself fails validation.
- Breaking changes: tightening constraints such as a lower
maximumdoes not rewrite stored objects. They are only validated again when someone updates them.
Exercise
A user applies a WebApp with spec.image: nginx and no resources field. Your schema defines resources.cpu with default: "100m" but resources itself has no default. What is spec.resources.cpu in the stored object, and what one-line change fixes it?
Show answer
The field is absent, because nested defaults only apply when the parent object exists. Add default: {} to the resources property. The server then creates the empty object and applies the cpu default inside it.