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.

    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?