如何从Go程序获取/更新Kubernetes自定义资源?

I'm looking for the go equivalent of:

kubectl get some-custom-resource-kind some-custom-resource -o yaml > file.yaml
Modify the yaml file...
kubectl apply -f file.yaml

Kubernetes has a client go library for standard resource kinds.

And various vendors have client go libraries for their custom resources.

But I need to get/update a resource kind that doesn't have a publicly available client go library. The logic is implemented in bash script today and I'm trying to move that function to a go controller.

Seems like it there should be a straightforward way in go to do the equivalent of kubectl.

Thanks, Paul

1个回答

For any type, including your CRDs, use client.Client.

From the documentation:

// Using a typed object.
pod := &corev1.Pod{}
// c is a created client.
_ = c.Get(context.Background(), client.ObjectKey{
    Namespace: "namespace",
    Name:      "name",
}, pod)
pod.SetFinalizers(append(pod.GetFinalizers(), "new-finalizer"))
_ = c.Update(context.Background(), pod)

// Using a unstructured object.
u := &unstructured.Unstructured{}
u.SetGroupVersionKind(schema.GroupVersionKind{
    Group:   "apps",
    Kind:    "Deployment",
    Version: "v1",
})
_ = c.Get(context.Background(), client.ObjectKey{
    Namespace: "namespace",
    Name:      "name",
}, u)
u.SetFinalizers(append(u.GetFinalizers(), "new-finalizer"))
_ = c.Update(context.Background(), u)

You could just as easily swap in SomeCustomResourceKind:

myCR := &v1alpha1.SomeCustomResourceKind{}

// c is a created client.Client
_ = c.Get(context.TODO(), client.ObjectKey{
  Namespace: "namespace",
  Name:      "some-custom-resource", }, myCR)

myCR.MyProperty = "NewValue"

_ = c.Update(context.TODO(), myCR)

You mentioned you're trying to move this functionality from a bash script to a Go controller, so it would be worth checking out the Kubebuilder project, which can scaffold out a controller for you (and any additional APIs you might need). It creates fully functional controllers with the controller-runtime Client and wires up all the reconciliation logic to manage your CRDs.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐