Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

293
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda