https://github.com/kubernetes/client-go.git
wget https://studygolang.com/dl/golang/go1.10.3.linux-amd64.tar.gz
tar xf go1.10.3.linux-amd64.tar.gz -C /usr/local/
vim /etc/profile
# Go
export GOROOT=/usr/local/go
export PATH=$PATH:$GOROOT/bin
export GOPATH=/root/gopath
source /etc/profile
创建对应目录
mkdir -p /root/gopath
mkdir -p /root/gopath/src
mkdir -p /root/gopath/pkg
mkdir -p /root/gopath/bin
go version
go version go1.10.3 linux/amd64
go get -v k8s.io/client-go/
go get -v k8s.io/apimachinery/
https://github.com/kubernetes/client-go/blob/master/examples/out-of-cluster-client-configuration/main.go
var kubeconfig *string
if home := homeDir(); home != ""{
kubeconfig = flag.String("kubeconfig", filepath.Join(home, "go", "src", "go-k8s", "config"), "(optional) absolute path to the kubeconfig file")
}else {
kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
}
flag.Parse()
config,err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
fmt.Println(err.Error())
}
https://github.com/kubernetes/client-go/blob/master/kubernetes/clientset.go
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
fmt.Println(err.Error())
}
fmt.Println("Connect kubernetes Successful!!!")
注意:Pods() 方法中 namespace 不指定则获取 Cluster 所有 Pod 列表
pods, err := clientset.CoreV1().Pods("").List(metav1.ListOptions{})
pod.ObjectMeta.Name
pod.Status.PodIP
pod.Spec.NodeName
package main
import (
"os"
"fmt"
"flag"
"path/filepath"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
func homeDir() string {
if h := os.Getenv("HOME"); h != "" {
return h
}
return os.Getenv("USERPROFILE")
}
func main() {
var kubeconfig *string
if home := homeDir(); home != ""{
// 配置 k8s 集群 kubeconfig 配置文件,默认位置 $HOME/.kube/config
kubeconfig = flag.String("kubeconfig", filepath.Join(home, "go", "src", "go-k8s", "config"), "(optional) absolute path to the kubeconfig file")
}else {
kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
}
flag.Parse()
config,err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
fmt.Println(err.Error())
}
_, err = kubernetes.NewForConfig(config)
if err != nil {
fmt.Println(err.Error())
}
fmt.Println("Connect kubernetes Successful!!!")
}