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

huangapple go评论94阅读模式
英文:

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>}}
英文:

I am using Velero to create and backup and restore, Velero has controllers which get triggered when I can create the custom objects.

import veleroApi &quot;github.com/vmware-tanzu/velero/pkg/apis/velero/v1&quot;

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

But how can I submit this custom object to the Kube API server?

I used API client to apply the changes:

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

But I am getting:

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:&lt;nil&gt; 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:&lt;nil&gt; IncludeClusterResources:&lt;nil&gt; Hooks:{Resources:[]}} Status:{Phase: ValidationErrors:[] Warnings:0 Errors:0 FailureReason: StartTimestamp:&lt;nil&gt; CompletionTimestamp:&lt;nil&gt; Progress:&lt;nil&gt;}}

答案1

得分: 2

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

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

记录下 API 和版本 以及 Kind,例如:

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

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

  1. 检查您从第一步得到的 API 版本 是否在 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" // 您可以从步骤 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{})
英文:

If you would like to create a client for custom object follow the following steps:

  1. Describe the custom resource for which you would like to create a rest client:
kubectl describe CustomResourceDefinition &lt;custom resource definition name&gt;

Note down the API and version and the Kind, as an example it would look like:

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

Here, apiextensions.k8s.io is API and v1 is the version.

  1. Check if the API version that you got from step 1 is in the list of APIs:
kubectl get --raw &quot;/&quot;
  1. Create the client:
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: &quot;&lt;API&gt;&quot;, Version: &quot;&lt;version&gt;&quot;}
	cfg.GroupVersion = &amp;gv
	cfg.APIPath = &quot;/apis&quot; // 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
}

Alternatively, check the answer from kozmo here


For Velero you can reuse the client they have.

As an example take a look at this code:

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

huangapple
  • 本文由 发表于 2021年11月18日 23:41:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/70022742.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定