CentOS 安装go client调用Kubernetes API
生活随笔
收集整理的這篇文章主要介紹了
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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Kubernetes 1.20 报错:“
- 下一篇: VMware ubuntu20.04 s