如何打印 Kubebuilder 中定义的状态字段以在使用 Kubectl 时显示

How to print Status fields defined in Kubebuilder to show up when using Kubectl

我如何必须指定 +kubebuilder:printcolumn 之类的注释才能将列添加到命令 kubectl get my-crd.my-group.my-domain.com 的输出中?

我有一个 CRD(自定义资源定义),其中包含通常的 struct 规范和状态(类似于此处 https://book.kubebuilder.io/cronjob-tutorial/new-api.html#adding-a-new-api 的 Kubebuilder 教程中的解释)。

我有这样的 状态 struct

type ScheduleSetStatus struct {
    // When was the last time the Schedule Set
    // was successfully deployed.
    LastDeployTime string `json:"lastDeployTime"` // metav1.Time
    // The CronJobs that have been successfully deployed
    DeployedCronJobs []string `json:"deployedCronJobs"`
    // The CronJobs that had errors when the deployment
    // has been attempted.
    ErroredCronJobs map[string]string `json:"erroredCronJobs"` // TODO `error` JSON serialisable
}

其中有几个问题:

时间字段

切片字段[]string和map字段map[string]string

解决方案是添加代码以更新资源状态 控制器的 协调器方法 - Reconcile(ctx context.Context, req ctrl.Request),像这样:

    // Update the status for "last deploy time" of a ScheduleSet
    myStruct.Status.LastDeployTime = metav1.Time{Time: time.Now().UTC()} // https://book.kubebuilder.io/cronjob-tutorial/api-design.html?highlight=metav1.Time#designing-an-api
    if err := r.Status().Update(ctx, &myStruct); err != nil {
        log.Error(err, "unable to update status xyz")
        return ctrl.Result{}, err
    }

Kubebuilder的特殊注解就可以了:

//+kubebuilder:printcolumn:name="Last Deploy",type="date",JSONPath=`.status.lastDeployTime`

此外,Go 切片和 Go 地图开箱即用,评论如下:

...

    DeployedCronJobs []string `json:"deployedCronJobs"`

...

    ErroredCronJobs map[string]string `json:"erroredCronJobs"`
...

//+kubebuilder:printcolumn:name="Deployed CJs",type=string,JSONPath=`.status.deployedCronJobs`
//+kubebuilder:printcolumn:name="Errored CJs",type=string,JSONPath=`.status.erroredCronJobs`