How do I get/update a Kubernetes custom resource from a go program?

9/24/2019

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

-- Paul Bennett
go
kubernetes

1 Answer

9/24/2019

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.

-- erstaples
Source: StackOverflow