创建/获取自定义 Kubernetes 资源。

8

我希望使用Go语言创建自定义Kubernetes资源,该应用程序已部署在Kubernetes集群中。我想要创建例如以下的资源:

    apiVersion: configuration.konghq.com/v1
    kind: KongPlugin
    metadata:
      name: add-response-header
    config:
      add:
        headers:
        - "demo: injected-by-kong"
    plugin: response-transformer

到目前为止,我总是使用以下代码创建“标准”资源,例如带有密码的机密资源:

     CreateSecret(name string, data map[string]string) error {
 confs, err := rest.InClusterConfig()
        if err != nil {
            panic(err)
        }
        clientset, err = kubernetes.NewForConfig(confs)
        i := clientset.CoreV1()
        if _, err := i.Secrets(namespace).Create(&v1.Secret{
            TypeMeta:   metav1.TypeMeta{
                Kind:       "Secret",
                APIVersion: "v1",
            },
            ObjectMeta: metav1.ObjectMeta{
                Name:   name,
            },
            StringData: data,
            Type:       "Opaque",
        }); err != nil {
            return err
        }
}

此外,我尝试使用以下代码获取资源:

b, err := clientset.RESTClient().Get().Namespace(namespace).Resource("KongPlugin").DoRaw()

我遇到了以下错误:

the server could not find the requested resource (get KongPlugin)

当我在命令行中发送请求 k get KongPlugin,我就可以查看所有资源。

NAME                PLUGIN-TYPE           AGE
add-proxy-headers   request-transformer   3h34m

那么如何查看自定义资源?


您可能会发现这个答案有用 https://dev59.com/WWwMtIcB2Jgan1zn4x1b#70026818 - Vishrant
1个回答

17

对于RESTClient

Get:

您必须完全指定到自定义资源的路径。使用fluent接口。

data, err := clientset.RESTClient().
        Get().
        AbsPath("/apis/<api>/<version>").
        Namespace("<namespace>").
        Resource("kongplugins").
        Name("kongplugin-sample").
        DoRaw(context.TODO())

或者手动指定

data, err := clientset.RESTClient().
        Get().
        AbsPath("/apis/<api>/<version>/namespaces/<namespace>/kongplugins/kongplugin-sample").
        DoRaw(context.TODO())

您可以在自定义资源的selfLink中找到AbsPath

创建:

例如,您可以使用AbsPath post编组数据。

kongPlugin := &KongPlugin{
        TypeMeta: metav1.TypeMeta{
            APIVersion: "<api>/<version>",
            Kind:       "KongPlugin",
        },
        ObjectMeta: metav1.ObjectMeta{
            Name:      "kongplugin-sample",
            Namespace: "<namespace>",
        },
        ...}}

body, err := json.Marshal(kongPlugin)

data, err := clientset.RESTClient().
        Post().
        AbsPath("/apis/<api>/<version>/namespaces/<namespace>/kongplugins").
        Body(body).
        DoRaw(context.TODO())

由于方法 Body(obj interface{}) 的参数arg是一个空接口,根据文档可以使用不同类型的参数: k8s.io/client-go/rest - func (*Request) Body


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接