通过clientcmd.BuildConfigFromFlags("", "/Users/username/.kube/config")获取rest.Config
通过kubernetes.NewForConfig(config)获取clientset
clientset.资源组名.资源名.List(context.TODO(),metav1.ListOptions{})
package main
import (
"context"
"fmt"
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() {
var config *rest.Config
config, err := clientcmd.BuildConfigFromFlags("", "/Users/4paradigm/.kube/config")
if err != nil {
fmt.Println(err)
}
clientset, err2 := kubernetes.NewForConfig(config)
if err2 != nil {
fmt.Println(err2)
}
namespaceList, err3 := clientset.CoreV1().Namespaces().List(context.TODO(), metav1.ListOptions{})
if err3 != nil {
fmt.Println(err3)
}
for k, ns := range namespaceList.Items {
fmt.Println(k, ns.Name)
}
}