How do I programtically validate a go structure that has kubebuilder validation markers? #4063
Replies: 1 comment
-
Hi @stack123-afk, When you use markers like This validation is enforced by the Kubernetes API server when you create or update resources via the API. For instance, when you run However, if you want to validate the spec/CR during reconciliation in your controller or directly within your Go code, you'll need to implement this validation manually in the controller's reconcile loop or by using webhooks. Here's an example of how you can implement this validation in Go, such as: func (spec *ToySpec) Validate() error {
if len(spec.Name) < 1 {
return errors.New("name is too short ... must be >= 1")
}
if len(spec.Name) > 15 {
return errors.New("name is too long... It must be <= 15")
}
return nil
} Also, you can consider to do validations using WebHooks (https://book.kubebuilder.io/reference/webhook-overview), i.e.:
Also, see: https://book.kubebuilder.io/cronjob-tutorial/webhook-implementation And see that the docs are using methods which are deprecated in the controller-runtime, so if you decide to use webhooks, I would suggest you follow the approach of the PR: #4060 The proposed changes in the docs done in this PR: https://github.com/kubernetes-sigs/kubebuilder/pull/4061/files also might be helpful for you understand it. By last, if you do not understand the concept of the reconcile I would recommend you ensure that you read the Getting Started at least: https://book.kubebuilder.io/getting-started (30 min) and https://book.kubebuilder.io/cronjob-tutorial/gvks I hope that helps you out. |
Beta Was this translation helpful? Give feedback.
-
Say I have the following structure:
I wanna do something like this:
Is this currently possible?
Beta Was this translation helpful? Give feedback.
All reactions