Get and modify yaml file from OpenShift API of the persisten volume in golang

3/18/2019

I am trying to modify the yaml file of a persistent volume in OpenShift through the API in Go(lang), I have the following

    pv, err := clientset.CoreV1().PersistentVolumes().List(metav1.ListOptions{})


    for _, persV := range pv.Items {
        // Check status persistent volume
        pvStatus, err := clientset.CoreV1().PersistentVolumes().Get(persV.Name, metav1.GetOptions{})
        if err != nil {
            panic(err.Error())
        }

        patch := []byte(`{"spec":{"template":{"spec":{"containers":[{"persistentVolumeReclaimPolicy":"Retain"}]}}}}`)
        a := fmt.Sprintf("%s", patch)
        fmt.Println(a)
        _, err = clientset.CoreV1().PersistentVolumes().Patch(persV.Name, types.StrategicMergePatchType, patch)
}

my persistent volume yaml

apiVersion: v1
kind: PersistentVolume
metadata:
...
...
...
persistentVolumeReclaimPolicy: Retain
status:
  phase: Released

How could I get the yaml file and modify it from my actual pvStatus? I would like to change persistentVolumeReclaimPolicy: Retain to persistentVolumeReclaimPolicy: Delete

-- Iago Santos
api
go
kubernetes
openshift

1 Answer

3/19/2019

Basically my error was constructing the patch []byte value, the script should look like

 pv, err := clientset.CoreV1().PersistentVolumes().List(metav1.ListOptions{})


    for _, persV := range pv.Items {
        // Check status persistent volume
        pvStatus, err := clientset.CoreV1().PersistentVolumes().Get(persV.Name, metav1.GetOptions{})
        if err != nil {
            panic(err.Error())
        }

        patch := []byte(`{"spec": {"persistentVolumeReclaimPolicy": "Delete"}}`)
        _, err = clientset.CoreV1().PersistentVolumes().Patch(persV.Name, types.StrategicMergePatchType, patch)
-- Iago Santos
Source: StackOverflow