go client-go 连接k8s
准备kubeconfig文件,自行准备
安装依赖包
go get k8s.io/client-go@v0.20.10
开始连接
const (
kubeConfig = "config/kubectl.kubeconfig"
)
func main(){
conf, err := clientcmd.BuildConfigFromFlags("", kubeConfig)
if err != nil {
fmt.Println("获取kubeconfig错误 ", err)
}
clientSet, err := kubernetes.NewForConfig(conf)
if err != nil {
fmt.Println("clientSet错误 ", err)
}
pods, err := clientSet.CoreV1().Pods("default").List(context.TODO(), metav1.ListOptions{})
if err != nil {
fmt.Println("获取pod异常 ", err)
}
for _, pod := range pods.Items {
fmt.Println(pod.Name, pod.Namespace, pod.CreationTimestamp)
}
}
执行则可以打印pod的信息
web-6559b6cdfb-48p6g default 2022-05-06 16:23:57 +0800 CST
web-6559b6cdfb-fjht5 default 2022-05-06 16:21:26 +0800 CST
web-6559b6cdfb-v2ccq default 2022-05-06 16:22:34 +0800 CST