1.下载client-go
https://github.com/kubernetes/client-go
2.如果在本地使用client-go访问k8s 需要把访问授权配置config下载到本地可访问目录
服务器文件一般在:/root/.kube/config
3.下载client-go 版本最后与k8s版本一致
go get k8s.io/client-go@v0.23.3
4.示例代码:
// 测试client-go
package main
import (
"context"
"fmt"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
func main() {
//创建配置 第一个参数配置文件名 不填使用默认配置文件名kubeconfig 第二个参数 配置文件路径 clientcmd.RecommendedHomeFile 是默认路径
//client-go客户端需要使用配置文件来访问k8s 以便进行授权访问 window本地访问服务器apiServer 需要把服务器上的config下载到本地
//服务器默认地址/root/.kube/config 下载放到本地能访问的目录下
config, err := clientcmd.BuildConfigFromFlags("", "D:\\golang\\client-go-study\\config")
//打印默认路径 默认地址:/root/.kube/config
println(clientcmd.RecommendedHomeFile)
if err != nil {
println("配置文件地址:", clientcmd.RecommendedHomeFile, err)
panic("获取配置文件失败")
}
//restClient, err := rest.RESTClientFor(config)
// 创建 Kubernetes 客户端
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
fmt.Println("Error creating Kubernetes client:", err)
return
}
// 使用客户端进行操作
// 例如,获取所有 Pod 的信息
pods, err := clientset.CoreV1().Pods("default").List(context.Background(), metav1.ListOptions{})
if err != nil {
fmt.Println("Error getting Pods:", err)
return
}
// 打印 Pod 信息
for _, pod := range pods.Items {
fmt.Println(pod.Name)
}
}
5.informer用于监控和处理 Kubernetes 资源对象变化的组件。
informer示例:
//测试informer 对集群进行监听
package main
import (
"fmt"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/informers"
"k8s.io/client-go/tools/cache"
corev1 "k8s.io/api/core/v1"
)
func main() {
//创建配置文件
config, err := clientcmd.BuildConfigFromFlags("", "D:\\golang\\client-go-study\\config")
if err != nil {
fmt.Println(err)
panic(err)
}
//创建clientSet
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
fmt.Println("Error creating Kubernetes client:", err)
return
}
//获取informer 第二个参数是默认重新同步周期 这个工厂返回所有命名空间的资源
//factory := informers.NewSharedInformerFactory(clientset, 0)
//获取指定命名空间的资源
factory := informers.NewSharedInformerFactoryWithOptions(clientset, 0, informers.WithNamespace("dev"))
//监听pod资源的informer
informer := factory.Core().V1().Pods().Informer()
//注册事件处理函数 来处理对应资源的事件
informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
fmt.Println("Pod added:", obj.(*corev1.Pod).Name)
},
UpdateFunc: func(oldObj, newObj interface{}) {
fmt.Println("Pod updated:", newObj.(*corev1.Pod).Name)
},
DeleteFunc: func(obj interface{}) {
fmt.Println("Pod deleted:", obj.(*corev1.Pod).Name)
},
})
//启动informer
stopCh := make(chan struct{})
factory.Start(stopCh)
<- stopCh
}
部署到集群运行
1.修改配置文件
//创建配置文件 首先从默认目录创建,此配置可在master节点启动
//如果是pod里执行 需要使用集群内配置 rest.InClusterConfig
config, err := clientcmd.BuildConfigFromFlags("", clientcmd.RecommendedHomeFile)
if err != nil {
fmt.Println(err)
//如果此程序运行在集群内部 使用上边在集群外获取配置文件是会报错的
//集群内部部署 使用serviceAccount进行授权验证
inClusterConfig, err := rest.InClusterConfig()
if err != nil {
log.Fatalln("con't get config")
}
config = inClusterConfig
}
配置Dockerfile 在项目根目录创建Dockerfile 内容如下
#golang运行基础镜像
FROM golang:alpine
#工作目录
WORKDIR /app
#使用国内代理
ENV GOPROXY=https://goproxy.cn
#复制文件到镜像
COPY . .
#运行构建 CGO_ENABLED=0 参数 以最小需求编译
RUN CGO_ENABLED=0 go build -o ingress-manage main.go
#运行
CMD ["./ingress-manage"]
在此目录执行如下命令:
#构建镜像
docker build -t client-go/ingress-manage:v1.1 .
#增加本地仓库名
docker tag client-go/ingress-manage:v1.1 192.168.140.135:5000/client-go/ingress-manage:v1.1
#推送到本地仓库
docker push 192.168.140.135:5000/client-go/ingress-manage:v1.1
#其他node节点pull镜像
docker pull 192.168.140.135:5000/client-go/ingress-manage:v1.1
启动deploy yaml配置
注意:要配置serviceAccountName: ingress-manage-sa 否则没有操作资源权限
并且前提是 已经配置好权限 后边附上权限配置
apiVersion: apps/v1
kind: Deployment
metadata:
name: client-go-demo
namespace: ingress-nginx
spec:
replicas: 1
selector:
matchLabels:
app: client-go-demo
template:
metadata:
labels:
app: client-go-demo
spec:
#配置权限
serviceAccountName: ingress-manage-sa
containers:
- name: client-go-demo
image: 192.168.140.135:5000/client-go/ingress-manage:v1.1
权限配置
apiVersion: v1
kind: ServiceAccount
metadata:
name: ingress-manage-sa
namespace: ingress-nginx
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: ingress-manage-role
namespace: ingress-nginx
rules:
- apiGroups:
- ""
resources:
- services
verbs:
- get
- list
- watch
- apiGroups:
- networking.k8s.io
resources:
- ingresses
verbs:
- get
- list
- watch
- create
- delete
- update
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: ingress-manage-rb
namespace: ingress-nginx
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: ingress-manage-role
subjects:
- kind: ServiceAccount
name: ingress-manage-sa
namespace: ingress-nginx
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: ingress-manage-clusterrole
rules:
- apiGroups:
- ""
resources:
- services
verbs:
- get
- list
- watch
- apiGroups:
- networking.k8s.io
resources:
- ingresses
verbs:
- get
- list
- watch
- create
- delete
- update
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: ingress-manage-cluster-rb
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: ingress-manage-clusterrole
subjects:
- kind: ServiceAccount
name: ingress-manage-sa
namespace: ingress-nginx
小技巧: 通过命令创建配置文件
#参数 -dry-run=client 客户端模拟运行 不会真正执行指令 而是生成配置文件
kubectl create serviceaccount ingress-manage-sa --namespace=ingress-nginx --dry-run=client -o yaml > ingress-manage-sa.yaml
kubectl create role ingress-manage-role --verb=get,list,watch,create,delete,update --resource=ingress,service --namespace=ingress-nginx --dry-run=client -o yaml
kubectl create rolebinding ingress-manage-rb --role=ingress-manage-role --serviceaccount=ingress-nginx:ingress-manage-sa --namespace=ingress-nginx --dry-run=client -o yaml