K
Q

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

September 23, 2019

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.

-- Dagang Wei
kubernetes

1 Answer

September 24, 2019

It should be as easy as this:

<!-- language: go -->
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.

<!-- language: go -->
    import (
      metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    )

    type MyCustomResource struct {
      metav1.TypeMeta `json:",inline"`
      // ... other stuff
    }
-- erstaples
Source: StackOverflow