日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

CentOS 安装go client调用Kubernetes API

發布時間:2025/3/11 编程问答 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 CentOS 安装go client调用Kubernetes API 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

CentOS 安裝 Go環境并配置goproxy

wget https://dl.google.com/go/go1.14.4.linux-amd64.tar.gz tar -xzvf go1.14.4.linux-amd64.tar.gz -C /usr/local/ mkdir -p /home/gopath cat >> /etc/profile <<EOF export GOROOT=/usr/local/go export GOPATH=/home/gopath export PATH=\$PATH:\$GOPATH/bin EOF source /etc/profile go version go env -w GO111MODULE=on go env -w GOPROXY=https://goproxy.cn,direct

在工程中新建一個名為go.mod的文件,在其中加入module和require兩個內容,如圖所示:

module go2go 1.15require k8s.io/client-go kubernetes-1.15.0


然后新建你的main.go文件,就可以在程序中調用clien-go工具包了。在第一次運行程序后,client-go工具包的相關組件就會被自動拽取到本地環境中。只是此后所有需要用到client-go的程序中都須加入go.mod文件。

5. 在k8s集群外讀取pod資源示例

package mainimport ("flag""fmt""os""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" )func main() {var kubeconfig *stringif home := homeDir(); home != "" {kubeconfig = flag.String("kubeconfig", filepath.Join(home, "src", "go-kubernetes", "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 kubeconfigconfig, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)if err != nil {panic(err.Error())}// create the clientsetclientset, err := kubernetes.NewForConfig(config)if err != nil {panic(err.Error())}for {pods, err := clientset.CoreV1().Pods("default").List(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.Messagenamespace := ""pod := "example-xxxxx"_, err = clientset.CoreV1().Pods(namespace).Get(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)} }func homeDir() string {if h := os.Getenv("GOPATH"); h != "" {return h}return os.Getenv("USERPROFILE") }

執行結果準確:

總結

以上是生活随笔為你收集整理的CentOS 安装go client调用Kubernetes API的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。