2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Client-go is a client library released and maintained by k8s for developers to interact with kubernetes. It supports CRUD operations (create, read, update, delete) on k8s resources, event monitoring and processing, and access to the context and configuration of the kubernetes cluster.
Client go is a client machine that is independent of the kubernetes cluster but interacts with the cluster. Install the go environment on this machine and establish a connection with kubernetes.
Install the go environment on the new node (in my case, it is a virtual machine). First, download the go installation package from the official website.All releases - The Go Programming Language
Since I installed the server version of the virtual machine, I used the curl command to download the installation package when installing the go environment. Because I need to determine the compatibility of the go environment with the k8s cluster, I need to check the k8s version of the cluster.
[root@master ~]# kubectl version --short
Client Version: v1.23.1
Server Version: v1.23.1
Check the official kubernetes documentation and find that it matches version 1.19.5 of go
- [root@client ~]# curl -L -O https://go.dev/dl/go1.19.5.linux-amd64.tar.gz
- % Total % Received % Xferd Average Speed Time Time Time Current
- Dload Upload Total Spent Left Speed
- 100 75 100 75 0 0 131 0 --:--:-- --:--:-- --:--:-- 131
- 100 65.7M 100 65.7M 0 0 3446k 0 0:00:19 0:00:19 --:--:-- 3513k
- [root@client ~]# file go1.22.5.linux-amd64.tar.gz
- # 验证下载文件的类型是否为压缩包
- go1.22.5.linux-amd64.tar.gz: gzip compressed data, max compression, original size modulo 2^32 232839680 gzip compressed data, unknown method, has CRC, extra field, has comment, encrypted, from FAT filesystem (MS-DOS, OS/2, NT), original size modulo 2^32 232839680
- [root@client ~]# rm -rf /usr/local/go && tar -C /usr/local -xzf go1.22.5.linux-amd64.tar.gz
Add go to the environment variable and check the go version to determine whether go is installed successfully.
- [root@client ~]# export PATH=$PATH:/usr/local/go/bin
- [root@client ~]# go version
- go version go1.19.5 linux/amd64
Add go to the environment variables persistently and write the above export PATH=... to the system file.
- [root@client ~]# vim ~/.bashrc
- [root@client ~]# source ~/.bashrc
If you are using Kubernetes version >= v1.17.0, please use the corresponding v0.x.y tag. For example, k8s.io/[email protected] corresponds to Kubernetes v1.20.4. My version is 1.23.1, so download the corresponding client-go version:
go get k8s.io/client-go@v0.23.1
The go mod file is created and go mode support is enabled:
- go mod init <module-name>
- export GO111MODULE=on
Then an initial go.mod file is created, which contains the module name and go version information. As the project is deployed or dependencies are added, go is automatically updated, and the go.mod file is automatically updated to record all dependencies and their versions, and a go.sum file is generated to ensure the consistency and integrity of the dependencies. Therefore, the go.mod file will gradually accumulate all the dependencies and version information required by the project.
Write the main.go file
- package main
-
- import (
- "flag"
- "fmt"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/client-go/kubernetes"
- "k8s.io/client-go/tools/clientcmd"
- "context"
- )
-
- func main() {
- // 配置 k8s 集群外 kubeconfig 配置文件
- var kubeconfig *string
- kubeconfig = flag.String("kubeconfig", "/etc/k8scoonfig/config", "absolute path to the kubeconfig file")
- namespace := flag.String("namespace","default","the namespace to list the pod from")
- flag.Parse()
-
- // use the current context in kubeconfig
- config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
- if err != nil {
- panic(err.Error())
- }
-
- // create the clientset
- clientset, err := kubernetes.NewForConfig(config)
- if err != nil {
- panic(err.Error())
- }
-
- // 获取集群中所有 Pod 列表
- pods, err := clientset.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{})
- if err != nil {
- panic(err.Error())
- }
- fmt.Printf("There are %d pods in the k8s clustern", len(pods.Items))
-
- // 获取指定 namespace 中的 Pod 列表
- pods, err = clientset.CoreV1().Pods(*namespace).List(context.TODO(), metav1.ListOptions{})
- if err != nil {
- panic(err)
- }
- fmt.Printf("There are %d pods in namespace %sn", len(pods.Items), namespace)
- for _, pod := range pods.Items {
- fmt.Printf("Name: %s, Status: %s, CreateTime: %vn", pod.Name, pod.Status.Phase, pod.CreationTimestamp)
- }
- }
When the specified namespace is monitor-sa, you can see that client-go successfully captures the number of pods in the namespace in the cluster.
- [root@client client_go_examples]# ./app -kubeconfig=/etc/k8scoonfig/config -namespace="monitor-sa"
- There are 18 pods in the k8s cluster
- There are 3 pods in namespace monitor-sa
- Name: node-exporter-jb9jp, Status: Running, CreateTime: 2024-07-06 11:47:33 +0000 UTC
- Name: node-exporter-kpvxd, Status: Running, CreateTime: 2024-07-06 11:47:33 +0000 UTC
- Name: node-exporter-pwdw4, Status: Running, CreateTime: 2024-07-06 11:47:33 +0000 UTC
Download kubectl. Note that the location where you save the download is where you will reference it later, so it is best to remember the save path and do not save it in the download folder.https://storage.googleapis.com/kubernetes-release/release/v1.18.0/bin/windows/amd64/kubectl.exe
Then add it to the environment variables, where kube is the folder where kubectl.exe is stored.
Open the Windows command line and test whether kubectl is working properly.
Configure kube-config and copy the config file copied to the Linux system to Windows. My directory is C:/user/.kube/config. Then configure it in vscode.
Download client-go locally, then download the go plugin and the code runner plugin in vscode:
Then press cstrl+shift+p to enter the search line of vscode and install the go plugin dependency. Search for Go:install/update tools
If this happens, you need to set environment variables. Set the following four environment variables, where go_path is the directory where the go code you want to run is stored, and go_root is the directory where you downloaded go.
Check the path. If the following items are present, then it is normal:
At this time, try to download GO: install/update tools again, and it will be successful.
After successful installation, install client-go in the gopath directory
- go get k8s.io/client-go@v0.23.1
- go get k8s.io/apimachinery@v0.23.1
- #使用 go mod tidy 确保所有依赖项已被正确下载并添加到项目中:
- go mod tidy
- go run main.go
Found that the operation was successful: