how to reuse k8s validation in my own CRD controller

4/9/2020

I created an CRD like this:

import v1 "k8s.io/api/core/v1"

type ApplicationSpec struct {
    Name string `json:"name"`

    PodSpec v1.PodSpec `json:"podSpec"`

    ...
}

notice that I reused PodSpec from core apigroup in my CRD

To avoid user apply invalid yaml files, I decided to add validation logic in my CRD controller, for simple fields like Name, it's easy to check it's correctness using regex, while for complex and native kind like PodSpec, since k8s already have validation logic for that, I feel the right way is reuse that in my controller, but how can I do that?

-- DiveInto
kubebuilder
kubernetes
openapi

2 Answers

4/10/2020

Also desire such a functionality to be provided as a library. There is a comment about using go get for k8s.io/kubernetes upstream. https://github.com/kubernetes/kubernetes/issues/80316#issuecomment-512991205 And the issue that is caused by using wrong configuration for PodTemplateSpec could be found here https://github.com/googleforgames/agones/issues/1298 Namely: we create a CRD successfully, however it become unhealthy later because pod could not be created.

-- Alexander Apalikov
Source: StackOverflow

4/9/2020

You can reuse the upstream ValidatePodSpec directly.

You would need to import a couple packages first:

import (
    "k8s.io/kubernetes/pkg/apis/core/validation"
    "k8s.io/apimachinery/pkg/util/validation/field"
)

Then make use of ValidatePodSpec in your controller method:

errs := validation.ValidatePodSpec(instance.podSpec, field.NewPath("podSpec"))
-- snormore
Source: StackOverflow