Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

295
Vistas
Patching a pvc using go client

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
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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.

over 4 years ago · Santiago Trujillo Denunciar

0

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"
}
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda