如何在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. 描述要为其创建rest客户端的自定义资源:
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,您可以重用他们的客户端。

举个例子,看看这个代码:

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

相关内容

  • 没有找到相关文章

最新更新