导语:通过client-go获取k8s集群的namespace和node
go get k8s.io/client-go@v0.18.2
go get k8s.io/api/auditregistration/v1alpha1@v0.18.2
go get k8s.io/client-go/tools/clientcmd@v0.18.2
# 查看资源在哪个下
kubectl api-resources
kubectl get nodes
main.go
package main
import (
"context"
"fmt"
"log"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func main() {
fmt.Println("k8s client")
configPath := "./config"
config, err := clientcmd.BuildConfigFromFlags("", configPath)
if err != nil {
log.Fatal(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err)
}
nodeList, err := clientset.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{})
if err != nil {
panic(err)
}
for _, node := range nodeList.Items {
fmt.Printf("%s\t%s\t%s\t%s\t%s\t%s\t%s\t,\n",
node.Name,
node.Status.Phase,
node.Status.Addresses,
node.Status.NodeInfo.OSImage,
node.Status.NodeInfo.KubeletVersion,
node.Status.NodeInfo.OperatingSystem,
node.Status.NodeInfo.Architecture,
)
}
}
go run main.go
namespace获取
# 添加
namespaceList, err := clientset.CoreV1().Namespaces().List(context.TODO(), metav1.ListOptions{})
if err != nil {
panic(err)
}
for _, namespace := range namespaceList.Items {
fmt.Println("k8s namespace")
fmt.Printf("%s\t%s\t%s\t\n",
namespace.Name,
namespace.CreationTimestamp,
namespace.Status.Phase,
)
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)