很简单的问题,我如何在当前go代码运行的地方获得Pod?
我需要它是因为出于某种原因,我需要直接对Pod的代码执行ping操作,而不是使用我的常规端点(即负载平衡器)。
我当前的配置:
apiVersion: v1 kind: Service metadata: name: web-socket-service-api spec: ports: # Port that accepts gRPC and JSON/HTTP2 requests over HTTP. - port: 8080 targetPort: 8080 protocol: TCP name: grpc # Port that accepts gRPC and JSON/HTTP2 requests over HTTP. - port: 8081 targetPort: 8081 protocol: TCP name: rest # Port that accepts WebSockets. - port: 8082 targetPort: 8082 protocol: TCP name: websocket selector: app: web-socket-service-api type: LoadBalancer --- apiVersion: extensions/v1beta1 kind: Deployment metadata: name: web-socket-service-api spec: replicas: 3 template: metadata: labels: app: web-socket-service-api spec: containers: - name: web-socket-service-api image: gcr.io/[PROJECT]/web-socket-service-api:latest ports: - containerPort: 8080 - containerPort: 8081 - containerPort: 8082
我试过了
/* metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" */ func GetContainerIP() string { // creates the in-cluster config config, err := rest.InClusterConfig() if err != nil { panic(err.Error()) } // creates the clientset clientset, err := kubernetes.NewForConfig(config) if err != nil { panic(err.Error()) } log.Println("checking pods") pods, err := clientset.CoreV1().Pods("default").List(metav1.ListOptions{}) if err != nil { panic(err.Error()) } b, _ := json.Marshal(pods) log.Println(string(b)) for _, pod := range pods.Items { log.Println(pod.Name, pod.Status) pod, err := clientset.CoreV1().Pods("default").Get(pod.Name, metav1.GetOptions{}) if err != nil { panic(err.Error()) } log.Println(pod.Status) } log.Println("checked pods") return "" }
但我可悲的是
紧急:禁止使用pods:用户“ system:serviceaccount:default:default”无法在名称空间“ default”中的API组“”中列出资源“ pods”
而且我找不到修复它的方法或任何有关它的教程。
片刻后我找到了答案,但完全忘了在这里发布!
请注意,如果您不在Kubernetes环境中,它将崩溃
import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "os" "os/signal" "time" ) // // Pod infos // func GetPodDetails() (IP string, name string) { // creates the in-cluster config config, err := rest.InClusterConfig() if err != nil { panic(err.Error()) } // creates the clientset clientset, err := kubernetes.NewForConfig(config) if err != nil { panic(err.Error()) } IP = "" for { if IP != "" { break } else { log.Printf("No IP for now.\n") } pods, err := clientset.CoreV1().Pods("default").List(metav1.ListOptions{}) if err != nil { panic(err.Error()) } for _, pod := range pods.Items { pod, _ := clientset.CoreV1().Pods("default").Get(pod.Name, metav1.GetOptions{}) if pod.Name == os.Getenv("HOSTNAME") { IP = pod.Status.PodIP } } log.Printf("Waits...\n") time.Sleep(1 * time.Second) } name = os.Getenv("HOSTNAME") log.Printf("Trying os.Getenv(\"HOSTNAME/IP\"): [%s][%s]\n", name, IP) return IP, name }