You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.1 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package test
import (
"context"
"k8s-manager/handler/common"
"log"
"k8s.io/client-go/kubernetes/scheme"
corev1 "k8s.io/api/core/v1"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
func RestClientPods() {
// 1. 获取RestClient
// 加载配置
config, err := clientcmd.BuildConfigFromFlags("", "../"+common.KubeConfigPath)
if err != nil {
log.Fatalln(err)
}
// 完成基础配置
// api 路径
config.APIPath = "api"
// 组版本
config.GroupVersion = &corev1.SchemeGroupVersion
// 约定的编解码器(序列化器)
config.NegotiatedSerializer = scheme.Codecs
// 获取 RestClient
restClient, err := rest.RESTClientFor(config)
if err != nil {
log.Fatalln(err)
}
// 2. 发出获取Pods的请求
// 结果对象
podList := &corev1.PodList{}
// 请求配置参数method选项
namespace := "kube-system"
if err := restClient.Get().
Resource("pods").
Namespace(namespace).
Do(context.Background()).
Into(podList); err != nil {
log.Fatalln(err)
}
// 3. 处理获取的响应
for _, pod := range podList.Items {
log.Printf("Name: %s Status: %s\n", pod.Name, pod.Status.Phase)
}
}