How to assign default value for Enum type

4.4k views Asked by At

From this Go code, I am generating the CRD yaml. I am using following structure in Go. I want to assign default value for parameters 'Size' and 'Case' from one of the enum options. Assigning // +kubebuilder:validation:default:=512 does not take effect in generated yaml file. Is there any way in kubebuilder, we can assign default value for enum?

type Options struct {
    // +kubebuilder:validation:default:=512
    // +kubebuilder:validation:Enum=64;128;256;512
    Size int64 `json:"Size"`
    
    // +kubebuilder:validation:Enum=caseA;caseB
    // +kubebuilder:validation:default:=caseA
    Case string `json:"case"`
}   



Generated yaml without default value
---------------
 case:
     enum:
      - caseA
      - caseB
     type: string

 Size:
     enum:
      - 64
      - 128
      - 256
      -512
     format: int64
     type: integer
2

There are 2 answers

0
gtz On

i'm doing something along those lines:

    // +kubebuilder:validation:Optional
    // +kubebuilder:validation:Enum=foo;bar
    // +kubebuilder:default:=none 
    Qux string `json:qux`

resulting in yaml that looks like:

              qux:
                default: foo
                enum:
                - foo
                - bar
                type: string

so i figure making the field optional is key.

0
user4744669 On

I think you have to add omitempty to the json tag, otherwise it fills it with the default 0 value for the type