Update:
I found that my code actually working. The reason that reconcile loop get false
at first is because I have another operator existing in my cluster and doing boolean flipping automatically. After deleted that operator, my code works as expected.
This question is related with Kubernetes and Operator-SDK. Let's say I have a Custom Resource which spec is shows as following:
apiVersion: my.example.com/v1alpha1
kind: MyStore
metadata:
name: mystore
spec:
name: "sample-store"
address: "sample-address"
zip: "sample-zip"
open: true
Where the last field open
is boolean type used to indicate whether the store is open or not. In reconcile loop of my operator, I would like to know whether a CR of MyStore
kind was explicitly set value of open
field. For example:
- If the value CR's
open
field has been explicitly set astrue
orfalse
, then reconcile loop should take this value directly. - If the CR does not have
open
field explicitly set, or this field is not existing, reconcile loop should consider the default value ofopen
astrue
.
Currently I tried this way, which is set the type of open
field as pointer of boolean in my struct:
type MyStoreSpec struct {
Name string `json:"name"`
Address string `json:"address"`
Zip string `json:"zip"`
Open *bool `json:"open"` // Here I use *bool as type
}
type MyStore stuct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec MyStoreSpec `json:"spec,omitempty"`
}
Then in reconcile loop I check the existing of open
field like this:
store := &examplev1beta1.MyStore{}
r.client.Get(context.TODO(), request.NamespacedName, store)
if store.Spec.Open == nil {
a := true
store.Spec.Open = &a
}
The idea of above code is to check whether the pointer of open
field exists: if pointer is null, set true
to open
field. And the idea is from this question Go: How to check if a struct property was explicitly set to a zero value?
But above code is not working as I expected: if open
field of a CR is not exists (not have value be explicitly set), the value of store.Spec.Open
will be parsed as false
but not nil
.
Is there any other ways to do the field value checking?