How to read Volumesnapshot object (or any K8s object)

7/7/2020

I want to read & parse Volumesnapshot object (or any K8s object) in go. I tried to take reference from https://github.com/kubernetes/client-go .

I am trying to add custom annotations in VolumeSnapshot CRD metadata as

apiVersion: snapshot.storage.k8s.io/v1beta1
kind: VolumeSnapshot
metadata:
  name: new-snapshot-test
  **annotation:**
        **test:Tushar**
spec:
  volumeSnapshotClassName: csi-hostpath-snapclass
  source:
    persistentVolumeClaimName: pvc-test

I also have a custom CSI driver. I need my CSI driver to look for that volumneSnapshot in K8s api server and parse this custom annotation and then process accordingly.

-- Scorpio
go
kubernetes

1 Answer

7/7/2020

You can follow any of the examples in the Github repo here. For example using the dynamic/unstructured way (code snippet based on this):

func main() {
	var kubeconfig *string
	if home := homedir.HomeDir(); home != "" {
		kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
	} else {
		kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
	}
	flag.Parse()

	namespace := "default"

	config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
	if err != nil {
		panic(err)
	}
	client, err := dynamic.NewForConfig(config)
	if err != nil {
		panic(err)
	}

	volumesnapshotRes := schema.GroupVersionResource{Group: "snapshot.storage.k8s.io", Version: "v1beta1", Resource: "volumesnapshots"}

	// List VolumeSnapshots
	prompt()
	fmt.Printf("Listing volume snapshots in namespace %q:\n", apiv1.NamespaceDefault)
	list, err := client.Resource(volumesnapshotRes).Namespace(namespace).List(context.TODO(), metav1.ListOptions{})
	if err != nil {
		panic(err)
	}
	for _, d := range list.Items {
    ...
        // do whatever with the items (print, etc)
    }
    // Finish up
    ...
-- Rico
Source: StackOverflow