将 Pod 规范的数据检索到结构变量中



我一直在尝试检索pod详细信息并将这些详细信息填充到结构的字段中。但是,在将详细信息填充到结构中时,我确实遇到错误。

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
}
}
}

我知道这是我可能错过的基本东西。请建议并更正我的代码。提前谢谢。

代码在这里。

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 configuration
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: %sn", pod.ObjectMeta.GetName(), pod.ObjectMeta.GetNamespace())
}
}

运行此代码。

$ 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

您可以在此处查看客户端GO示例。

最新更新