controller-tools
controller-tools copied to clipboard
✨ feat: Add resource field-scoped fields
This feature adds resource field-scoped fields.
Why?
While working on Google Managed Service for Prometheus, we identified a need to have namespaced and cluster-scoped versions of the same structs.
How
This solution adds a new marker on fields that appear conditionally depending on the top-level CRD scope.
For example, we may have a struct:
type SecretSelector struct {
// These fields appear regardless of scope.
Name string `json:"name"`
Key string `json:"key"`
// This field only appears for cluster-scoped objects, since we could use the namespace of the top-level object.
// +kubebuilder:field:scope=Cluster
Namespace string `json:"namespace"`
}
For a namespaced CRD, the namespace field will not be generated as part of the OpenAPI specification because the namespace field is marked as being cluster-scoped.
The opposite is true as well. A field can be marked namespaced and will not be generated for cluster-scoped resources.
Defaults apply too. A CRD is considered namespaced by default, so cluster-scoped fields will not appear.
Implementation
The implementation is admittedly a bit hacky. A special property is inserted at schema parse-time, and later removed when processing the resource. I couldn't figure out a better way to do this. The comments in the code should describe why it was done this way.