kubernetes/client-go
作者:互联网
git clone https://github.com/kubernetes/client-go.git
root@ubuntu:~/client-go/examples/out-of-cluster-client-configuration# go build -o app . go: downloading k8s.io/api v0.0.0-20210702094336-49e8721f8489
o: downloading k8s.io/api v0.0.0-20210702094336-49e8721f8489 root@ubuntu:~/client-go/examples/out-of-cluster-client-configuration# ./app There are 32 pods in the cluster Pod example-xxxxx in namespace default not found ^C root@ubuntu:~/client-go/examples/out-of-cluster-client-configuration#
func main() { var kubeconfig *string if home := homedir.HomeDir(); 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()) } // create the clientset clientset, err := kubernetes.NewForConfig(config) if err != nil { panic(err.Error()) } for { pods, err := clientset.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{}) if err != nil { panic(err.Error()) } fmt.Printf("There are %d pods in the cluster\n", len(pods.Items)) // Examples for error handling: // - Use helper functions like e.g. errors.IsNotFound() // - And/or cast to StatusError and use its properties like e.g. ErrStatus.Message namespace := "volcano-system" pod := "volcano-scheduler-7f48dddb8f-8g6b5" _, err = clientset.CoreV1().Pods(namespace).Get(context.TODO(), pod, metav1.GetOptions{}) if errors.IsNotFound(err) { fmt.Printf("Pod %s in namespace %s not found\n", pod, namespace) } else if statusError, isStatus := err.(*errors.StatusError); isStatus { fmt.Printf("Error getting pod %s in namespace %s: %v\n", pod, namespace, statusError.ErrStatus.Message) } else if err != nil { panic(err.Error()) } else { fmt.Printf("Found pod %s in namespace %s\n", pod, namespace) } time.Sleep(10 * time.Second) } }
root@ubuntu:~/client-go/examples/out-of-cluster-client-configuration# ./app There are 32 pods in the cluster Found pod volcano-scheduler-7f48dddb8f-8g6b5 in namespace volcano-system There are 32 pods in the cluster Found pod volcano-scheduler-7f48dddb8f-8g6b5 in namespace volcano-system ^C
volcano-system volcano-admission-6cc49fdc5-5zgzs 1/1 Running 0 23h 10.244.29.8 bogon <none> <none> volcano-system volcano-admission-init-qgh9b 0/1 Completed 0 23h 10.244.29.6 bogon <none> <none> volcano-system volcano-controllers-5f5c4f4785-8dbgl 1/1 Running 0 23h 10.244.29.7 bogon <none> <none> volcano-system volcano-scheduler-7f48dddb8f-8g6b5 1/1 Running 0 23h 10.244.29.5 bogon <none> <none>
标签:kubernetes,err,namespace,kubeconfig,client,go,volcano,pod 来源: https://www.cnblogs.com/dream397/p/14976963.html