CodeBlanks Logo Icon CodeBlanks

Validation

Learn CRD validation rules.

Validation

A CRD's openAPIV3Schema validates on the API server: types, required fields, limits, allowed values. An invalid object is rejected before being saved; the controller is spared from dealing with broken data:

spec:
  type: object
  required: [veritabani, takvim]
  properties:
    veritabani: {type: string, minLength: 1}
    takvim:     {type: string, pattern: "^[0-9*/,-]+( [0-9*/,-]+){4}$"}
    saklamaGun: {type: integer, minimum: 1, maximum: 365, default: 7}
    tur:        {type: string, enum: [tam, artimli]}

CEL rules

For cross-field rules, CEL expressions (x-kubernetes-validations) are written into the validation definition. Complex validation can be done without writing a webhook:

spec:
  type: object
  x-kubernetes-validations:
    - rule: "self.tur != 'artimli' || self.saklamaGun <= 30"
      message: "artımlı yedekler en fazla 30 gün saklanır"

$ kubectl apply -f yedek.yaml
The Yedek "magaza-gece" is invalid: spec: Invalid value: artımlı yedekler en fazla 30 gün saklanır

Practice Tighten the validation

Write the spec property of a CRD validation definition (starting with spec:): type: object; required: [veritabani, takvim]; under properties, veritabani (type: string), takvim (type: string) and saklamaGun (type: integer, minimum: 1, maximum: 365).

Starter code

terminal
# buraya yaz

Sample solution

terminal
spec:
  type: object
  required: [veritabani, takvim]
  properties:
    veritabani:
      type: string
    takvim:
      type: string
    saklamaGun:
      type: integer
      minimum: 1
      maximum: 365

Expected output

customresourcedefinition.apiextensions.k8s.io/yedekler.ornek.com configured
$ kubectl apply -f hatali-yedek.yaml
The Yedek "deneme" is invalid: spec.saklamaGun: Invalid value: 500: spec.saklamaGun in body should be less than or equal to 365

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens if a Yedek with saklamaGun: 500 is applied?

  • The API server rejects it with "must be less than or equal to 365" Correct answer
  • It's clipped to 365
  • It's saved and the controller fixes it
  • It's ignored

Explanation: Validation happens before saving.

2 Specify the required fields.

Question
spec:
  type: object
  ____: [veritabani, takvim]
Answer
spec:
  type: object
  required: [veritabani, takvim]

Explanation: required is the list of required fields in OpenAPI.

3 Match.

Term Meaning
required Required fields
minimum/maximum Number limits
enum Allowed values
x-kubernetes-validations CEL rule

All lessons in Expert