英文:
Operator SDK - Update CreationTimestamp
问题
我目前正在使用Golang和Operator SDK编写一个Kubernetes Operator。
为了知道资源的创建是否超时,我检查当前资源的CreationTimestamp
属性。在成功的Update
之后,我想要更新该资源的CreationTimestamp
,但是当我这样做时,什么都不会发生,CreationTimestamp
保持不变...
我的Reconcile
循环大致如下:
func (r *MyReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
myObject := &v1alpha1.My{}
err := r.Get(ctx, req.NamespacedName, myObject)
if err != nil {
// 处理错误
}
// 如果标记为删除
// 做一些操作
// ...
// 如果标记为更新
myObject.SetCreationTimestamp(v1.Now())
err = r.Update(ctx, configMap) // 更新我更改的所有字段,但不包括CreationTimestamp...
if err != nil {
println("ERR:", err.Error()) // 不会抛出错误
}
println(myObject.CreationTimestamp) // 仍然是旧的时间戳,而不是v1.Now()
// ...
}
或者是否有其他方法来跟踪资源上次调谐的时间?
英文:
I am currently writing a Kubernetes Operator using Golang and the Operator SDK.
In order to know if the creation of a resource has timed out I check the CreationTimestamp
property of my current resource. After a successful Update
I want to update the CreationTimestamp
of that resource, but when I do that, nothing happens and the CreationTimestamp
stays the same...
My Reconcile
loop looks something like this:
func (r *MyReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
myObject := &v1alpha1.My{}
err := r.Get(ctx, req.NamespacedName, myObject)
if err != nil {
// do something
}
//if marked to be deleted
//do something
//...
//if marked to be updated
myObject.SetCreationTimestamp(v1.Now())
err = r.Update(ctx, configMap) //updates all fields that I changed except for CreationTimestamp...
if err != nil {
println("ERR:", err.Error()) //doesnt get thrown
}
println(myObject.CreationTimestamp) //still the old timestamp instead of v1.Now()
//...
}
Or is there any other way to track when the resource was reconciled the last time?
答案1
得分: 0
我不认为有一种方法可以实现这个,但我找到了一个解决方法。
在你的CRD
中,字段metadata.annotations
可以以map[string]string
的形式存储信息,这样就不会被覆盖。
所以我创建了一个名为CreationTimestamp
的字段,并在我的Go代码中使用myObject.ObjectMeta.Annotations["creationTimestamp"]
来检索它。
我可以像这样更新值:myObject.ObjectMeta.Annotations["creationTimestamp"] = "newvalue"
,然后通过执行Update
来保存更改。
英文:
I dont think there is a way to achieve this, but I found a workaround.
In your CRD
the field metadata.annotations
can store information in a map[string]string
that wont be overwritten.
So I created a field called CreationTimestamp
and retrieve it in my go code with myObject.ObjectMeta.Annotations["creationTimestamp"]
.
I can update the value like this: myObject.ObjectMeta.Annotations["creationTimestamp"] = "newvalue"
and then doing an Update
to save the changes
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论