Home > database >  kubectl get pod <pod> -n <namespace> -o yaml in kubernetes client-go
kubectl get pod <pod> -n <namespace> -o yaml in kubernetes client-go

Time:07-04

Now i have Pods as Kubernetes structs wiht the help of the command

pods , err := clientset.CoreV1().Pods("namespace_String").List(context.TODO(), metav1.ListOptions{})

now i do i get it as individual yaml files which command should i use

for i , pod := range pods.Items{
    if i==0{
        t := reflect.TypeOF(&pod)
        for j := 0; j<t.NumMethod(); j  {
            m := t.Method(j)
            fmt.Println(m.Name)
}
}
}

this function will print the list of functions in the pod item which should i use

Thanks for the answer

CodePudding user response:

The yaml is just a representation of the Pod object in the kubernetes internal storage in etcd. With your client-go what you have got is the Pod instance, of the type v1.Pod. So you should be able to work with this object itself and get whatever you want, for example p.Labels() etc. But if for some reason, you are insisting on getting a yaml, you can do that via:

import (
  "sigs.k8s.io/yaml"
)

b, err := yaml.Marshal(pod)
if err != nil {
  // handle err
}
log.Printf("Yaml of the pod is: %q", string(b))

Note that yaml library coming here is not coming from client-go library. The documentation for the yaml library can be found in: https://pkg.go.dev/sigs.k8s.io/yaml#Marshal

Instead of yaml if you want to use json, you can simply use the Marshal function https://pkg.go.dev/k8s.io/apiserver/pkg/apis/example/v1#Pod.Marshal provided by the v1.Pod struct itself, like any other Go object.

CodePudding user response:

To get individual pod using client-go:

pod, err := clientset.CoreV1().Pods("pod_namespace").Get(context.TODO(),"pod_name", metav1.GetOptions{})
if err!=nil {
  log.Fatalln(err)
}
// do something with pod
  • Related