Creating empty Kubernetes resource struct when knowing the resource kind/type only (in golang)

4/14/2019

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{} ?

-- Roland Huß
go
kubernetes

2 Answers

4/15/2019

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

-- Antoine Cotten
Source: StackOverflow

4/14/2019

There is no pretty way to do this.

This would require two steps:

  1. Building a type map: map[string]reflect.Type

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?

  1. 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

-- Sean F
Source: StackOverflow