kubernetes custom resource definition required field

4/13/2018

I am trying to write a kubernetes crd validation schema. I have an array (vc) of structures and one of the fields in those structures is required (name field).

I tried looking through various examples but it doesn't generate error when name is not there. Any suggestions what is wrong ?

vc:
  type: array
  items:
    type: object
    properties:
      name:
        type: string
      address:
        type: string
    required:
    - name
-- sacboy
kubernetes
kubernetes-custom-resources

1 Answer

11/18/2018

If you are on v1.8, you will need to enable the CustomResourceValidation feature gate for using the validation feature. This can be done by using the following flag on kube-apiserver:

--feature-gates=CustomResourceValidation=true

Here is an example of it working (I tested this on v1.12, but this should work on earlier versions as well):

The CRD:

apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: foos.stable.example.com
spec:
  group: stable.example.com
  versions:
    - name: v1
      served: true
      storage: true
  version: v1
  scope: Namespaced
  names:
    plural: foos
    singular: foo
    kind: Foo
  validation:
    openAPIV3Schema:
      properties:
        spec:
          properties:
            vc:
              type: array
              items:
                type: object
                properties:
                  name:
                    type: string
                  address:
                    type: string
                required:
                - name

The custom resource:

apiVersion: "stable.example.com/v1"
kind: Foo
metadata:
  name: new-foo
spec:
  vc:
  - address: "bar"
  1. Create the CRD.

kubectl create -f crd.yaml customresourcedefinition.apiextensions.k8s.io/foos.stable.example.com created

  1. Get the CRD and check if the validation field exists in the output. If it doesn't, you probably don't have the feature gate turned on.

kubectl get crd foos.stable.example.com -oyaml

  1. Try to create the custom resource. This should fail with:

kubectl create -f cr-validation.yaml

The Foo "new-foo" is invalid: []: Invalid value: map[string]interface {}{"metadata":map[string]interface {}{"creationTimestamp":"2018-11-18T19:45:23Z", "generation":1, "uid":"7d7f8f0b-eb6a-11e8-b861-54e1ad9de0be", "name":"new-foo", "namespace":"default"}, "spec":map[string]interface {}{"vc":[]interface {}{map[string]interface {}{"address":"bar"}}}, "apiVersion":"stable.example.com/v1", "kind":"Foo"}: validation failure list: spec.vc.name in body is required

-- Nikhita Raghunath
Source: StackOverflow