如何在 Kubernetes 中创建自定义对象?

How to create custom objects in Kubernetes?

我正在使用 Velero 创建、备份和恢复,Velero 有控制器,当我可以创建自定义对象时会触发这些控制器。

import veleroApi "github.com/vmware-tanzu/velero/pkg/apis/velero/v1"

restoreObj := veleroApi.Restore{
    TypeMeta:   metav1.TypeMeta{},
    ObjectMeta: metav1.ObjectMeta{
        DeletionGracePeriodSeconds: &gracePeriodSeconds,
    },
    Spec:       veleroApi.RestoreSpec{
        BackupName:              "backup-name-20211101",
        RestorePVs:              &restorePV,
    },
    Status:     veleroApi.RestoreStatus{},
}

但是如何将这个自定义对象提交到 Kube API 服务器?

我使用 API 客户端来应用更改:

apiClient.CoreV1().RESTClient().Patch(types.ApplyPatchType).Body(restoreObj).Do(context)

但我得到:

unknown type used for body: {TypeMeta:{Kind:Restore APIVersion:velero.io/v1} ObjectMeta:{Name: GenerateName: Namespace:velero SelfLink: UID: ResourceVersion: Generation:0 CreationTimestamp:0001-01-01 00:00:00 +0000 UTC DeletionTimestamp:<nil> DeletionGracePeriodSeconds:0xc000256018 Labels:map[] Annotations:map[] OwnerReferences:[] Finalizers:[] ClusterName: ManagedFields:[]} Spec:{BackupName:backup-name-20211101 ScheduleName: IncludedNamespaces:[] ExcludedNamespaces:[] IncludedResources:[] ExcludedResources:[] NamespaceMapping:map[] LabelSelector:nil RestorePVs:0xc0007a9088 PreserveNodePorts:<nil> IncludeClusterResources:<nil> Hooks:{Resources:[]}} Status:{Phase: ValidationErrors:[] Warnings:0 Errors:0 FailureReason: StartTimestamp:<nil> CompletionTimestamp:<nil> Progress:<nil>}}

如果您想为自定义对象创建客户端,请按照以下步骤操作:

  1. 描述您想为其创建休息客户端的自定义资源:
kubectl describe CustomResourceDefinition <custom resource definition name>

记下 API and versionKind,例如:

API Version:  apiextensions.k8s.io/v1
Kind:         CustomResourceDefinition

这里,apiextensions.k8s.io是API,v1是版本。

  1. 检查您从第 1 步获得的 API version 是否在 API 的列表中:
kubectl get --raw "/"
  1. 创建客户端:
func getClusterConfig() *rest.Config {
    config, err := rest.InClusterConfig()
    if err != nil {
        glog.Fatal(err.Error())
    }
    return config
}

func getRestClient() *rest.RESTClient {

    cfg := getClusterConfig()

    gv := schema.GroupVersion{Group: "<API>", Version: "<version>"}
    cfg.GroupVersion = &gv
    cfg.APIPath = "/apis" // you can verify the path from step 2

    var Scheme = runtime.NewScheme()
    var Codecs = serializer.NewCodecFactory(Scheme)
    cfg.NegotiatedSerializer = Codecs.WithoutConversion()

    restClient, err := rest.RESTClientFor(cfg)

    if err != nil {
        panic(err.Error())
    }
    return restClient
}

或者,查看 kozmo

的答案

对于 Velero,您可以重用他们拥有的客户端。

举个例子看看 this code:

restore, err := o.client.VeleroV1().Restores(restore.Namespace).Create(context.TODO(), restore, metav1.CreateOptions{})