код здесь.
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
func main() {
// creates the in-cluster config
config, err := rest.InClusterConfig()
if err != nil {
// creates the out-of-cluster config
var kubeconfig *string
if home := os.Getenv("HOME"); 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()
// use the current context in kubeconfig
config, err = clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
panic(err.Error())
}
}
// creates the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
// fetch all pod name, namespace in "default" namespace
pods, err := clientset.CoreV1().Pods("default").List(metav1.ListOptions{})
for _, pod := range pods.Items {
fmt.Printf("pod name: %s namespace: %s\n", pod.ObjectMeta.GetName(), pod.ObjectMeta.GetNamespace())
}
}
запустите этот код.
$ kubectl get pod
NAME READY STATUS RESTARTS AGE
nginx-pod 1/1 Running 0 92m
nginx-pod2 1/1 Running 0 21s
$ go run main.go
pod name: nginx-pod namespace: default
pod name: nginx-pod2 namespace: default
, и вы можете увидеть примеры клиентских go здесь .