kuberneteskubernetes-go-clientkubernetes-operatoroperator-sdkkubebuilder

How to generate Events for a certain resource Kubernetes Go Operator


I'm writing a Kubernetes Operator in Go and I would like to generate events in the same way Pods do, i.e. at each point of the reconciliation I want to write an event which can be examined using kubectl describe myresource.

I found the package that would allow me to do that, but I don't understand how to use it: https://github.com/kubernetes/client-go/blob/master/tools/record/event.go

Example skeleton code:

type MyResourceReconciler struct {
    client.Client
    Log    logr.Logger
    Scheme *runtime.Scheme
}

var logger logr.Logger

func (r *MyResourceReconciler) SetupWithManager(mgr ctrl.Manager) error {
    return ctrl.NewControllerManagedBy(mgr).
        Named("MyResource-controller").
        For(&v1.MyResource{}).
        Complete(r)
}

func (r *MyResourceReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
    logger = r.Log.V(0).WithValues("MyResource", req.NamespacedName)
    logger.Info("reconcile called")

    // TODO: Record event for req.NamespacedName

    return reconcile.Result{}, nil
}

Solution

  • The Kubebuilder v1 book has a good example on how to create and write Events using an EventRecorder from client-go.

    See Kubebuilder v1 book - Create Events and Write Events