I am trying to update a pvc label using go library's patch option from this interface.
Is there any example on how to use this? Also if the label is not there will patch also add the label?
I am looking to update/add my_label in below object:
kind: PersistentVolumeClaim
metadata:
annotations:
pv.kubernetes.io/bind-completed: "yes"
pv.kubernetes.io/bound-by-controller: "yes"
volume.beta.kubernetes.io/storage-class: ""
creationTimestamp: "2021-01-25T18:53:02Z"
finalizers:
- kubernetes.io/pvc-protection
labels:
my_label: my_value
It could be done the following way:
persVolC := client.CoreV1().PersistentVolumeClaims("default")
data := `
[
{ "op": "add", "path": "/metadata/labels/mylabel", "value": "myvalue" }
]
`
updatedPvc, err := persVolC.Patch(ctx, "name-of-pvc", types.JSONPatchType, []byte(data), meta_v1.PatchOptions{})
if err != nil {
log.Fatal(err)
}
Full example at go playground.
And here you can read about JSON patch standard.
This is an example in which we're going to iterate over the List of PersistentVolumeClaims in the default namespace, and we're going to set an specific label my_label: label_test to all of those Items. You can get an specific PVC instead of List all with the func Get(ctx context.Context, name string, opts metav1.GetOptions)
package main
import (
"context"
"fmt"
"log"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
func newClient(contextName string) (kubernetes.Interface, error) {
configOverrides := &clientcmd.ConfigOverrides{CurrentContext: contextName}
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
config, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, configOverrides).ClientConfig()
if err != nil {
return nil, err
}
return kubernetes.NewForConfig(config)
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
client, err := newClient("")
if err != nil {
log.Fatal(err)
}
label := make(map[string]string)
label["my_label"] = "label_test"
persVolC := client.CoreV1().PersistentVolumeClaims("default")
pvcs, err := persVolC.List(ctx, meta_v1.ListOptions{})
for _, pvc := range pvcs.Items {
vol := pvc.DeepCopy()
vol.ObjectMeta.Labels = label
upd, err := persVolC.Update(ctx, vol, meta_v1.UpdateOptions{})
if err != nil {
log.Fatal(err)
}
fmt.Println(upd)
}
}
If you want to check if a label exist and update it, you can replace vol.ObjectMeta.Labels = label by
if _, ok := vol.ObjectMeta.Labels["my_label"]; ok {
vol.ObjectMeta.Labels["my_label"] = "my_new_label"
}