Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert runtime.Object to a specific type?

Tags:

kubernetes

I'm writing a custom controller with Kubebuilder framework, in one method, I got an object of type runtime.Object, I know I should be able to convert it to the specific type say MyCustomResource, but I cannot figure out how from the doc.

like image 877
Dagang Avatar asked Sep 02 '25 05:09

Dagang


1 Answers

It should be as easy as this:

func convertToMyCustomResource(obj runtime.Object) *v1alpha1.MyCustomResource {
  myobj := obj.(*v1alpha1.MyCustomResource)
  return myobj
}

If this produces an error (e.g. Impossible type assertion), make sure MyCustomResource satisfies the runtime.Object interface; i.e.

  1. Run the controller-gen tool to generate the DeepCopyObject method

    go run vendor/sigs.k8s.io/controller-tools/cmd/controller-gen/main.go paths=./api/... object
    
  2. Add the "k8s.io/apimachinery/pkg/apis/meta/v1".TypeMeta field to the MyCustomResource struct, which implements the GetObjectKind method.

    import (
      metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    )

    type MyCustomResource struct {
      metav1.TypeMeta `json:",inline"`
      // ... other stuff
    }
like image 124
erstaples Avatar answered Sep 04 '25 19:09

erstaples