I have been trying to retrieve pod details & fill those details into fields of struct. However, i do get error while filling the details into a struct.
package main
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
// corev1"k8s.io/api/core/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
type PodsList struct{
podNamespace string
podName string
}
func main() {
var targetPods []TargetPodsList
config, inClusterConfigError := rest.InClusterConfig()
if inClusterConfigError != nil {
fmt.Println("Retrieval of K8s InCluster Config not successful")
log.Fatal(inClusterConfigError)
}
// Set k8s client configuration
clientset, clientSetError := kubernetes.NewForConfig(config)
if clientSetError != nil {
fmt.Println("K8s Client for Incluster Configuration not successful")
log.Fatal(clientSetError)
}
// Retrieve Pods for all target K8s nodes
for index := range targetNodes.TargetNodes {
targetPodsList, _ := clientset.CoreV1().Pods("").List(metav1.ListOptions{
FieldSelector: "spec.nodeName=" + someNodeName)
for podIndex := range targetPodsList.Items {
targetPods.podNamespace = targetPods[podIndex].podNamespace
targetPods.podName = targetPods[podIndex].podName
}
}
}
I know this is basic thing which i may be missing.
Please do suggest and correct my code.
Thanks in advance.
the code is here.
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
func main() {
// creates the in-cluster config
config, err := rest.InClusterConfig()
if err != nil {
// creates the out-of-cluster config
var kubeconfig *string
if home := os.Getenv("HOME"); home != "" {
kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
} else {
kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
}
flag.Parse()
// use the current context in kubeconfig
config, err = clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
panic(err.Error())
}
}
// creates the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
// fetch all pod name, namespace in "default" namespace
pods, err := clientset.CoreV1().Pods("default").List(metav1.ListOptions{})
for _, pod := range pods.Items {
fmt.Printf("pod name: %s namespace: %s\n", pod.ObjectMeta.GetName(), pod.ObjectMeta.GetNamespace())
}
}
run this code.
$ kubectl get pod
NAME READY STATUS RESTARTS AGE
nginx-pod 1/1 Running 0 92m
nginx-pod2 1/1 Running 0 21s
$ go run main.go
pod name: nginx-pod namespace: default
pod name: nginx-pod2 namespace: default
and you can see client-go examples here.