Sub topic 6
Validating resources at admission time
This chapter assumes you can write a CRD with a structural schema and apply custom resources with kubectl. Here you will add validation, so the API server rejects bad objects before they are stored.
Where validation happens
When you create or update a custom resource, the API server runs it through a fixed sequence. Validation of your CRD's schema and rules happens before the object reaches etcd. Your controller never sees an object that failed.
Defaulting runs first, so a default such as replicas: 1 is already in place when the rules are evaluated.
Schema constraints
The OpenAPI v3 schema covers single-field checks: type, required, minimum, maximum, enum, pattern, minLength and maxItems. They are cheap to evaluate and show up in kubectl explain, so use them first.
CEL validation rules
Some checks cannot be written as a schema constraint. These include comparing two fields and forbidding a change after creation. For these, add x-kubernetes-validations. Each entry has a CEL expression in rule. In the expression, self is the value at that schema location. CEL (Common Expression Language) runs inside the API server, so no webhook is needed.
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: webapps.example.com
spec:
group: example.com
scope: Namespaced
names:
plural: webapps
singular: webapp
kind: WebApp
versions:
- name: v1
served: true
storage: true
subresources:
status: {}
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
required: ["image"]
x-kubernetes-validations:
- rule: "!has(self.maxReplicas) || self.replicas <= self.maxReplicas"
message: "replicas must not exceed maxReplicas"
properties:
image:
type: string
minLength: 1
replicas:
type: integer
minimum: 0
default: 1
maxReplicas:
type: integer
minimum: 1
tier:
type: string
enum: ["frontend", "backend"]
region:
type: string
x-kubernetes-validations:
- rule: "self == oldSelf"
message: "region is immutable"
status:
type: object
properties:
readyReplicas:
type: integerThis CRD has three kinds of checks:
- The
enumandminimumconstraints are schema checks. - The rule on
speccompares two fields.has()guards the optionalmaxReplicas. - The rule on
regionis a transition rule. Any rule that mentionsoldSelfruns only on updates, soself == oldSelfmakes the field immutable once set.
Applying a WebApp with replicas: 5 and maxReplicas: 3 fails with the message replicas must not exceed maxReplicas. The object is not created.
Common errors
- Missing
has()on optional fields. Reading an absent field is an evaluation error, and the request is rejected. Guard optional fields. - Rules without a
message. Users then see the raw expression in the error. Always write a message. - Treating validation as authorization. Rules check object shape. They do not decide who may write.
- Expensive rules. The API server enforces a cost budget on CEL. Unbounded lists or strings can make the CRD fail to install until you add
maxItemsormaxLength. - Tightening rules on live data. Stored objects that already violate a new rule are not rejected until someone updates them, and then the update fails. Test new rules against existing resources.
When a check needs data from outside the object, such as another resource, use a validating webhook. A later chapter covers webhooks.
Exercise
A WebApp has spec.region: eu-west-1. A user runs kubectl apply with the same manifest but region: us-east-1. The CRD has the rule self == oldSelf on region. What happens, and why does creating a new WebApp with region: us-east-1 still work?
Show answer
The update is rejected with the message "region is immutable", because the rule compares the new value with the stored one. Creating a new object works because a rule that references oldSelf is a transition rule. It runs only on updates, and a create has no old value.