Nested defaults #3208
-
Hi, I've been investigating the way defaulting annotations work following a series of strange behaviour occurences in the operators I'm maintaining. We were making a series of small mistakes not following the k8s api conventions regarding optional fields but after fixing this, I'm still wondering about the following use case: I've made a dummy project to demonstrate the situation. type DefaultDemoSpec struct {
Foo string `json:"foo,omitempty"`
//+optional
Car *Car `json:"car,omitempty"`
}
type Car struct {
//+optional
//+kubebuilder:default:=50
Horsepower *int `json:"horsePower,omitempty"`
//+optional
//+kubebuilder:default:=4
Wheels *int `json:"wheels,omitempty"`
} I want to be able to get default values for my Car struct so that applying the following yaml: apiVersion: default.example.com/v1
kind: DefaultDemo
metadata:
name: demo
namespace: bar-iac-test
spec:
foo: "test" Would end up creating the following object: Spec:
Car:
Horse Power: 50
Wheels: 4
Foo: test The solution I have found is to repeat at least one of the default properties as a default object value above the type DefaultDemoSpec struct {
Foo string `json:"foo,omitempty"`
//+optional
//+kubebuilder:default:={wheels:4}
Car *Car `json:"car,omitempty"`
} I am not particularly satisfied with this solution as it involves duplicating the defaults. Is there a better way to do this ? Thank you for your time |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hi @tbarizien, The omitempty tag tells the Kubernetes API server (and the underlying Go JSON encoder) to omit the field from the output if it's empty. In Kubernetes CRDs, it's common to use omitempty for optional fields to keep the serialized output clean. When using omitempty in conjunction with default values, I understand that it can lead to some non-intuitive behavior. Following how I understand that it works:
Why it seems that controller-gen works in this way:
However, if you do not agree with? How to ask to change See that the markers ( https://book.kubebuilder.io/reference/markers ) are implemented by controller-gen (see the Makefile of your project and the targets make manifest and make generate). So, controller-gen is a binary build from the controller-tools, see: https://github.com/kubernetes-sigs/controller-tools
So, I am closing this one as sorted out. |
Beta Was this translation helpful? Give feedback.
Hi @tbarizien,
The omitempty tag tells the Kubernetes API server (and the underlying Go JSON encoder) to omit the field from the output if it's empty. In Kubernetes CRDs, it's common to use omitempty for optional fields to keep the serialized output clean.
When using omitempty in conjunction with default values, I understand that it can lead to some non-intuitive behavior.
Following how I understand that it works: