How can I create an empty struct of a certain Kubernetes resource when the resource kind/type is given as string ?
I.e.
var object *runtime.Object
object = factory.NewResourceFromKind("pod")
and object
should then contain &apiv1.Pod{}
?
Knowing the Kind
is not enough, however a combination of API Group + API Version + object Kind (GroupVersionKind
) would allow you to use the information contained in the default scheme.Scheme
variable to generate a new object.
package main
import (
"fmt"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/kubernetes/scheme"
)
func main() {
// apiVersion's syntax is "group/version" for non-core API groups
// e.g. "apps/v1"
podGvk := schema.FromAPIVersionAndKind("v1", "Pod")
obj, err := scheme.Scheme.New(podGvk) // error handling omitted
fmt.Printf("%T", obj)
/* prints '*v1.Pod' */
}
See godoc for func (*Scheme) New
There is no pretty way to do this.
This would require two steps:
You could either write your own code to go through each k8s api type and insert into a map, as in this answer: is there a way to create an instance of a struct from a string?
Or, you could use an extremely non-portable method to extract types from binaries, which allows you to avoid knowing which types to add to the map: How to discover all package types at runtime?
Use the map to instantiate. Lookup myType from a string using the map, then:
reflect.New(myType).Elem()
where myType is the instance of reflect.Type