-
Notifications
You must be signed in to change notification settings - Fork 461
Description
Hi,
I'm using kubebuilder to generate a CRD from the following type definition (minimized):
type CustomSpec struct {
// +optional
// +kubebuilder:default={}
Foo FooType `json:"foo,omitempty"`
}
type FooType struct {
// +optional
// +kubebuilder:default=false
Bar bool `json:"bar,omitempty"`
// +optional
// +kubebuilder:default=1
Baz int `json:"baz,omitempty"`
// +optional
// +kubebuilder:default=QUX
Qux string `json:"qux,omitempty"`
}This gives the following CRD (comments added manually):
# This is .spec.versions[0].schema.openAPIV3Schema.properties.spec
# Indentation has been brought down
spec:
properties:
foo:
# The following line is not present, but expected
# default: {}
properties:
bar:
default: false
type: boolean
baz:
default: 1
type: integer
qux:
default: QUX
type: string
type: object
type: objectThe issue I'm facing is that if I apply an empty spec for my custom resource, with spec: {} then foo only contains the golang type defaults, e.g. baz is 0 and qux is an empty string.
If I use spec: {foo: {}} then foo is populated with all the correct default values for its properties, however I don't want to force my clients to define foo.
If I modify the CRD manually (after controller-gen, but before kustomize) to add default: {} inside the CRD, everything behaves as expected, and an empty spec gives a correct CR when using kubectl get:
# kubectl get custom/object -o json | jq .spec
{
"foo": {
"bar": false,
"baz": 1,
"qux": "QUX"
}
}The current workaround I've found is to use the following annotation (which is non-ideal):
// +kubebuilder:default={baz: 1}
Foo FooType `json:"foo,omitempty"`This has the effect of defining foo with the correct defaults, but foo.baz takes the value defined in foo's default over baz's default, so this can override default values on properties if the defaults are changed.
It seems the main issue is that controller-gen parses {} as an empty slice, which json.Marshal then marshalls as null, which gets ignored when writing the CRD. Here's the code that scans the slice, it appears this edge case was considered but not implemented yet:
https://github.com/kubernetes-sigs/controller-tools/blob/master/pkg/markers/parse.go#L297
Hopefully this is fixable without breaking stuff, or maybe a cleaner workaround can be found 🙂