使用 client-go 配置客户端,使用包含集群上下文信息的 kubeconfig 文件来初始化客户端。以从在 Kubernetes 集群外部运行的应用程序向 Kubernetes API 进行身份验证。与kubectl命令使用 kubeconfig 文件对集群进行身份验证类似。
当前项目代码:代码参考
package main
import (
"context"
"flag"
"fmt"
"path/filepath"
"time"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/homedir"
)
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()
// 使用kubeconfig中的当前上下文,加载配置文件
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
panic(err.Error())
}
// 创建clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
// 遍历pods,list获取pod的数量
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))
//错误处理的例子:
// -使用helper函数,如errors.IsNotFound()
// -和/或转换为StatusError,并使用它的属性,如ErrStatus.Message
namespace := "default"
pod := "test-node-local-dns"
_, 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)
}
}
➜ client-go-k8s-cluster-external git:(master) ✗ ls
README.md go.mod go.sum main.go
运行go
项目
➜ client-go-k8s-cluster-external git:(master) ✗ go run main.go
There are 13 pods in the cluster
Pod test-node-local-dns in namespace default not found