如何提交通用的"runtime.Object"使用client-go进入Kubernetes API [英] How to Submit generic "runtime.Object" to Kubernetes API using client-go
问题描述
我正在使用的是Kubernetes v1.10的AWS EKS,并且正在使用client-go v7.0.0.
I'm using AWS' EKS which is Kubernetes v1.10 and I'm using client-go v7.0.0.
我想做的是解析一个文件中具有多个Kubernetes资源定义的.yml文件,并将这些资源提交给Kubernetes API.我可以使用此代码scheme.Codecs.UniversalDeserializer().Decode
成功解析文件,然后获得runtime.Object
数组.
What I'm trying to do is parse a .yml file with multiple Kubernetes resource definitions in a file and submit those resources to the Kubernetes API. I can successfully parse the files using this code scheme.Codecs.UniversalDeserializer().Decode
, and I get back an array of runtime.Object
.
我知道所有Kubernetes资源都符合runtime.Object
接口,但是我找不到将通用接口提交给API的方法.我见过的大多数方法都在Deployment,Pod等具体类型上使用这些方法.
I know that all the Kubernetes resources conform to the runtime.Object
interface, but I can't find a way to submit the generic interface to the API. Most methods I've seen use the methods on the concrete types like Deployment, Pod, etc.
我已经看到了像clientset.RESTClient().Put().Body(obj).Do()
这样的通用RESTClient周围的一些代码,但这是行不通的,我无法弄清.
I've seen some code around a generic RESTClient like this clientset.RESTClient().Put().Body(obj).Do()
, but that doesn't work and I can't figure it out.
我知道我的客户端集配置正确,因为我可以成功列出所有Pod.
I know my clientset is configured correctly because I can successfully list all Pods.
推荐答案
If you have a "generic" runtime.Object
, you can use the dynamic client in client-go for this. The dynamic client deals with unstructured.Unstructured
objects and all runtime.Object
s can be converted to it. Here is an example:
// create the dynamic client from kubeconfig
dynamicClient, err := dynamic.NewForConfig(kubeconfig)
if err != nil {
return err
}
// convert the runtime.Object to unstructured.Unstructured
unstructuredObj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)
if err != nil {
return err
}
// create the object using the dynamic client
nodeResource := schema.GroupVersionResource{Version: "v1", Resource: "Node"}
createdUnstructuredObj, err := dynamicClient.Resource(nodeResource).Namespace(ns).Create(unstructuredObj)
if err != nil {
return err
}
// convert unstructured.Unstructured to a Node
var node *corev1.Node
if err = runtime.DefaultUnstructuredConverter.FromUnstructured(createdUnstructuredObj, node); err != nil {
return err
}
这篇关于如何提交通用的"runtime.Object"使用client-go进入Kubernetes API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!