这一篇算是这个设计的开篇之作,做一个基于WEB的K8S资源调度评价模拟器,首先先学会使用代码编程方式访问API Server,这个基础知识自己补充,先上一个基本例子。用GO语言编程。
```bash
package main
import (
"context"
"fmt"
"k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
func main() {
// uses the current context in kubeconfig
// path-to-kubeconfig -- for example, /root/.kube/config
config, _ := clientcmd.BuildConfigFromFlags("", "C:\\Users\\HJW\\.kube\\config")
// creates the clientset
clientset, _ := kubernetes.NewForConfig(config)
// access the API to list pods
pods, _ := clientset.CoreV1().Pods("").List(context.TODO(), v1.ListOptions{})
fmt.Printf("There are %d pods in the cluster\n", len(pods.Items))
}
C:\Users\HJW\.kube\config是我自己WIN10电脑安装docker后装K8S环境之后默认的kubeconfig安装位置,如果是linux,可能在/etc/kubernetes/kubeconfig/kubelet.kubeconfig或者/root/.kube/config。
运行效果如下:
可以看出来返回了环境中的pod的数量
用powershell验证一下果然如此,client-go永远的神!!!!!!!!!!!!!!!!!
[https://kubernetes.io/zh/docs/tasks/administer-cluster/access-cluster-api/]这是K8S官方文档的介绍(https://kubernetes.io/zh/docs/tasks/administer-cluster/access-cluster-api/)