dongtuo3795 2019-09-24 16:08
浏览 152

如何从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条回答 默认 最新

  • dov6891 2019-09-24 17:09
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥20 fluent无法启动
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥50 Oracle Kubernetes服务器集群主节点无法访问,工作节点可以访问
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架
  • ¥15 有关sql server business intellige安装,包括SSDT、SSMS。