请选择 进入手机版 | 继续访问电脑版

[Golang] 利用 client-go工具调用kubernetes API接口的教程详解(v1.17版本)

[复制链接]
查看186 | 回复28 | 2021-9-15 01:55:01 | 显示全部楼层 |阅读模式
目次

阐明

可以调取k8s API 接口的工具有很多,这里我就先容 下

  1. client-go
复制代码

gitlab上client-go项目地址: https://github.com/kubernetes/client-go  

这个工具是由kubernetes官方指定维护的,大家可以放心利用

在这里插入图片形貌

效果

运行完成后,可以直接获取k8s集群信息等

在这里插入图片形貌

实现

1、拉取工具源码

留意 事项:https://github.com/kubernetes/client-go/blob/master/INSTALL.md

总结:肯定 要拉取跟集群对应版本的工具源码,比如我这里集群是1.17版本,那我就拉取17版本

  1. go get <a rel="external nofollow" target="_blank" href="https://www.jb51.net/mailto:k8s.io/client-go@v0.17.0">k8s.io/client-go@v0.17.0</a>
复制代码

我是1.17版本的集群,全部 依靠 文件放在这了,可以直接利用 client-go k8s1.17 api

2、创建目次 布局

在这里插入图片形貌

集群的脚色 设置 文件(默认在/root/.kube/config)
kube/config

查询代码实例

查询pod信息

查看

  1. ferry
复制代码
定名 空间下pod的信息,pod名字、pod的IP

vim kube-api.go

  1. package main
  2. import (
  3. "fmt"
  4. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  5. "k8s.io/client-go/kubernetes"
  6. "k8s.io/client-go/tools/clientcmd"
  7. )
  8. func main() {
  9. config, err := clientcmd.BuildConfigFromFlags("", "kube/config")
  10. if err != nil {
  11. panic(err)
  12. }
  13. client, _ := kubernetes.NewForConfig(config)
  14. pods ,err := client.CoreV1().Pods("ferry").List(metav1.ListOptions{})
  15. if err != nil {
  16. fmt.Println(err)
  17. return
  18. }
  19. for _,v := range pods.Items {
  20. fmt.Printf(" 命名空间是:%v\n pod名字:%v\n IP:%v\n\n",v.Namespace,v.Name,v.Status.PodIP)
  21. }
  22. }
复制代码

主动 关联依靠

  1. go mod tidy
复制代码

运行效果

  1. $ go run kube-api.go
  2.  命名空间是:ferry
  3.  pod名字:ferry-backend-7949596679-h8lxb
  4.  IP:10.42.1.14
  5.  命名空间是:ferry
  6.  pod名字:ferry-mysql-8db8d49f7-6psbv
  7.  IP:10.42.1.11
复制代码

查询一个pod是否在一个定名 空间下

https://github.com/kubernetes/client-go/blob/master/examples/in-cluster-client-configuration/main.go
每3秒检查下

  1. nginx-74959fc858-cp48w
复制代码
是否在
  1. default
复制代码
定名 空间下

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "k8s.io/apimachinery/pkg/api/errors"
  6. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  7. "k8s.io/client-go/kubernetes"
  8. "k8s.io/client-go/tools/clientcmd"
  9. "time"
  10. )
  11. func main() {
  12. config, err := clientcmd.BuildConfigFromFlags("", "kube/config")
  13. if err != nil {
  14. panic(err)
  15. }
  16. clientset, err := kubernetes.NewForConfig(config)
  17. if err != nil {
  18. panic(err.Error())
  19. }
  20. for {
  21. // get pods in all the namespaces by omitting namespace
  22. // Or specify namespace to get pods in particular namespace
  23. pods, err := clientset.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{})
  24. if err != nil {
  25. panic(err.Error())
  26. }
  27. fmt.Printf("There are %d pods in the cluster\n", len(pods.Items))
  28. // Examples for error handling:
  29. // - Use helper functions e.g. errors.IsNotFound()
  30. // - And/or cast to StatusError and use its properties like e.g. ErrStatus.Message
  31. _, err = clientset.CoreV1().Pods("default").Get(context.TODO(), "nginx-74959fc858-cp48w", metav1.GetOptions{})
  32. if errors.IsNotFound(err) {
  33. fmt.Printf("Pod nginx-74959fc858-cp48w not found in default namespace\n")
  34. } else if statusError, isStatus := err.(*errors.StatusError); isStatus {
  35. fmt.Printf("Error getting pod %v\n", statusError.ErrStatus.Message)
  36. } else if err != nil {
  37. panic(err.Error())
  38. } else {
  39. fmt.Printf("Found nginx-74959fc858-cp48w pod in default namespace\n")
  40. }
  41. time.Sleep(3 * time.Second)
  42. }
  43. }
复制代码

运行效果

  1. $ go run kube-api.go
  2. There are 22 pods in the cluster
  3. Found nginx-74959fc858-cp48w pod in default namespace
  4. There are 22 pods in the cluster
  5. Found nginx-74959fc858-cp48w pod in default namespace
  6. There are 22 pods in the cluster
  7. Found nginx-74959fc858-cp48w pod in default namespace
  8. There are 23 pods in the cluster
  9. Found nginx-74959fc858-cp48w pod in default namespace
  10. There are 22 pods in the cluster
  11. Found nginx-74959fc858-cp48w pod in default namespace
  12. There are 22 pods in the cluster
  13. Found nginx-74959fc858-cp48w pod in default namespace
  14. There are 21 pods in the cluster
  15. \\在集群种手动删除了这个pod
  16. Pod nginx-74959fc858-cp48w not found in default namespace
  17. There are 21 pods in the cluster
  18. Pod nginx-74959fc858-cp48w not found in default namespace
复制代码

查询deployment服务范例 信息

查询

  1. default
复制代码
定名 空间下的deployment服务信息,服务名字、服务副本数

  1. package main
  2. import (
  3. "fmt"
  4. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  5. "k8s.io/client-go/kubernetes"
  6. "k8s.io/client-go/tools/clientcmd"
  7. )
  8. func main() {
  9. config, err := clientcmd.BuildConfigFromFlags("", "kube/config")
  10. if err != nil {
  11. panic(err)
  12. }
  13. client, _ := kubernetes.NewForConfig(config)
  14. deploymentList, err := client.AppsV1().Deployments("default").List(metav1.ListOptions{})
  15. if err != nil {
  16. fmt.Println(err)
  17. return
  18. }
  19. for _,v := range deploymentList.Items {
  20. fmt.Printf(" 命名空间是:%v\n deployment服务名字:%v\n 副本个数:%v\n\n",v.Namespace,v.Name,v.Status.Replicas)
  21. }
  22. }
复制代码

运行效果

  1. $ go run kube-api.go
  2.  命名空间是:default
  3.  deployment服务名字:nginx
  4.  副本个数:2
复制代码

创建deployment资源

https://github.com/kubernetes/client-go/blob/master/examples/create-update-delete-deployment/main.go

复制一个config文件到当前目次 下

在这里插入图片形貌

创建一个deployment范例 的nginx服务

vim deployment-create.go

  1. package main
  2. import (
  3. "context"
  4. "flag"
  5. "fmt"
  6. "path/filepath"
  7. appsv1 "k8s.io/api/apps/v1"
  8. apiv1 "k8s.io/api/core/v1"
  9. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  10. "k8s.io/client-go/kubernetes"
  11. "k8s.io/client-go/tools/clientcmd"
  12. "k8s.io/client-go/util/homedir"
  13. //
  14. // Uncomment to load all auth plugins
  15. // _ "k8s.io/client-go/plugin/pkg/client/auth"
  16. //
  17. // Or uncomment to load specific auth plugins
  18. // _ "k8s.io/client-go/plugin/pkg/client/auth/azure"
  19. // _ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
  20. // _ "k8s.io/client-go/plugin/pkg/client/auth/oidc"
  21. // _ "k8s.io/client-go/plugin/pkg/client/auth/openstack"
  22. )
  23. func main() {
  24. var kubeconfig *string
  25. if home := homedir.HomeDir(); home != "" {
  26. kubeconfig = flag.String("kubeconfig", filepath.Join("config"), "(optional) absolute path to the kubeconfig file")
  27. } else {
  28. kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
  29. }
  30. flag.Parse()
  31. config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
  32. if err != nil {
  33. panic(err)
  34. }
  35. clientset, err := kubernetes.NewForConfig(config)
  36. if err != nil {
  37. panic(err)
  38. }
  39. deploymentsClient := clientset.AppsV1().Deployments(apiv1.NamespaceDefault)
  40. deployment := &appsv1.Deployment{
  41. ObjectMeta: metav1.ObjectMeta{
  42. Name: "nginx-deployment",
  43. },
  44. Spec: appsv1.DeploymentSpec{
  45. Replicas: int32Ptr(2),
  46. Selector: &metav1.LabelSelector{
  47. MatchLabels: map[string]string{
  48. "app": "nginx",
  49. },
  50. },
  51. Template: apiv1.PodTemplateSpec{
  52. ObjectMeta: metav1.ObjectMeta{
  53. Labels: map[string]string{
  54. "app": "nginx",
  55. },
  56. },
  57. Spec: apiv1.PodSpec{
  58. Containers: []apiv1.Container{
  59. {
  60. Name: "web",
  61. Image: "nginx:1.12",
  62. Ports: []apiv1.ContainerPort{
  63. {
  64. Name: "http",
  65. Protocol: apiv1.ProtocolTCP,
  66. ContainerPort: 80,
  67. },
  68. },
  69. },
  70. },
  71. },
  72. },
  73. },
  74. }
  75. // Create Deployment
  76. fmt.Println("Creating deployment nginx...")
  77. result, err := deploymentsClient.Create(context.TODO(), deployment, metav1.CreateOptions{})
  78. if err != nil {
  79. panic(err)
  80. }
  81. fmt.Printf("Created deployment %q.\n", result.GetObjectMeta().GetName())
  82. }
复制代码

运行效果

  1. $ go run deployment-create.go
  2. Creating deployment nginx...
  3. Created deployment "nginx-deployment".
复制代码

更新deployment范例 服务

https://github.com/kubernetes/client-go/blob/master/examples/create-update-delete-deployment/main.go
更改服务的副本数,由上一步创建的2修改成1,并修改镜像由nginx1.12–>nginx1.13

  1. package main
  2. import (
  3. "context"
  4. "flag"
  5. "fmt"
  6. "path/filepath"
  7. apiv1 "k8s.io/api/core/v1"
  8. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  9. "k8s.io/client-go/kubernetes"
  10. "k8s.io/client-go/tools/clientcmd"
  11. "k8s.io/client-go/util/homedir"
  12. "k8s.io/client-go/util/retry"
  13. //
  14. // Uncomment to load all auth plugins
  15. // _ "k8s.io/client-go/plugin/pkg/client/auth"
  16. //
  17. // Or uncomment to load specific auth plugins
  18. // _ "k8s.io/client-go/plugin/pkg/client/auth/azure"
  19. // _ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
  20. // _ "k8s.io/client-go/plugin/pkg/client/auth/oidc"
  21. // _ "k8s.io/client-go/plugin/pkg/client/auth/openstack"
  22. )
  23. func main() {
  24. var kubeconfig *string
  25. if home := homedir.HomeDir(); home != "" {
  26. kubeconfig = flag.String("kubeconfig", filepath.Join("config"), "(optional) absolute path to the kubeconfig file")
  27. } else {
  28. kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
  29. }
  30. flag.Parse()
  31. config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
  32. if err != nil {
  33. panic(err)
  34. }
  35. clientset, err := kubernetes.NewForConfig(config)
  36. if err != nil {
  37. panic(err)
  38. }
  39. deploymentsClient := clientset.AppsV1().Deployments(apiv1.NamespaceDefault)
  40. retryErr := retry.RetryOnConflict(retry.DefaultRetry, func() error {
  41. // Retrieve the latest version of Deployment before attempting update
  42. // RetryOnConflict uses exponential backoff to avoid exhausting the apiserver
  43. result, getErr := deploymentsClient.Get(context.TODO(), "nginx-deployment", metav1.GetOptions{})
  44. if getErr != nil {
  45. panic(fmt.Errorf("Failed to get latest version of Deployment: %v", getErr))
  46. }
  47. result.Spec.Replicas = int32Ptr(1) // reduce replica count
  48. result.Spec.Template.Spec.Containers[0].Image = "nginx:1.13" // change nginx version
  49. _, updateErr := deploymentsClient.Update(context.TODO(), result, metav1.UpdateOptions{})
  50. return updateErr
  51. })
  52. if retryErr != nil {
  53. panic(fmt.Errorf("Update failed: %v", retryErr))
  54. }
  55. fmt.Println("Updated deployment nginx")
  56. }
  57. func int32Ptr(i int32) *int32 { return &i }
复制代码

运行效果

  1. $ go run deployment-update.go
  2. Updated deployment nginx
复制代码

在这里插入图片形貌

删除deployment范例 服务

删除上面创建的

  1. nginx-deployment
复制代码
资源,删除之前添加了确认语句

  1. package main
  2. import (
  3. "bufio"
  4. "context"
  5. "flag"
  6. "fmt"
  7. "os"
  8. "path/filepath"
  9. apiv1 "k8s.io/api/core/v1"
  10. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  11. "k8s.io/client-go/kubernetes"
  12. "k8s.io/client-go/tools/clientcmd"
  13. "k8s.io/client-go/util/homedir"
  14. //
  15. // Uncomment to load all auth plugins
  16. // _ "k8s.io/client-go/plugin/pkg/client/auth"
  17. //
  18. // Or uncomment to load specific auth plugins
  19. // _ "k8s.io/client-go/plugin/pkg/client/auth/azure"
  20. // _ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
  21. // _ "k8s.io/client-go/plugin/pkg/client/auth/oidc"
  22. // _ "k8s.io/client-go/plugin/pkg/client/auth/openstack"
  23. )
  24. func main() {
  25. var kubeconfig *string
  26. if home := homedir.HomeDir(); home != "" {
  27. kubeconfig = flag.String("kubeconfig", filepath.Join( "config"), "(optional) absolute path to the kubeconfig file")
  28. } else {
  29. kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
  30. }
  31. flag.Parse()
  32. config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
  33. if err != nil {
  34. panic(err)
  35. }
  36. clientset, err := kubernetes.NewForConfig(config)
  37. if err != nil {
  38. panic(err)
  39. }
  40. deploymentsClient := clientset.AppsV1().Deployments(apiv1.NamespaceDefault)
  41. prompt()
  42. fmt.Println("Deleting deployment nginx...")
  43. deletePolicy := metav1.DeletePropagationForeground
  44. if err := deploymentsClient.Delete(context.TODO(), "nginx-deployment", metav1.DeleteOptions{
  45. PropagationPolicy: &deletePolicy,
  46. }); err != nil {
  47. panic(err)
  48. }
  49. fmt.Println("Deleted deployment.")
  50. }
  51. func prompt() {
  52. fmt.Printf("-> Press Return key to continue, will delete!")
  53. scanner := bufio.NewScanner(os.Stdin)
  54. for scanner.Scan() {
  55. break
  56. }
  57. if err := scanner.Err(); err != nil {
  58. panic(err)
  59. }
  60. fmt.Println()
  61. }
  62. func int32Ptr(i int32) *int32 { return &i }
复制代码

运行效果

  1. $ go run deployment-delete.go
  2. -> Press Return key to continue, will delete! 这里点击回车后继续删除资源
  3. Deleting deployment nginx...
  4. Deleted deployment.
复制代码

在这里插入图片形貌

到此这篇关于利用 client-go工具调kubernetes API接口(v1.17版本)的文章就先容 到这了,更多相干 client-go调用kubernetes API内容请搜刮 脚本之家从前 的文章或继续欣赏 下面的相干 文章盼望 大家以后多多支持脚本之家!


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
回复

使用道具 举报

avatar 123457021 | 2021-9-28 20:02:04 | 显示全部楼层
admin楼主好聪明啊!
回复

使用道具 举报

avatar 123457848 | 2021-9-29 08:09:19 | 显示全部楼层
在这个版块混了这么久了,第一次看见这么给你的帖子!
回复

使用道具 举报

avatar 绣绣仙女酌 | 2021-10-1 22:16:19 | 显示全部楼层
admin楼主是一个神奇的青年!
回复

使用道具 举报

avatar 兴冲冲丈 | 2021-10-5 08:29:34 | 显示全部楼层
怎么我回帖都没人理我呢?
回复

使用道具 举报

avatar 没手棋进负 | 2021-10-5 21:45:10 | 显示全部楼层
每次看到admin楼主的帖子都有惊吓!
回复

使用道具 举报

avatar 冀苍鸾 | 2021-10-6 06:06:04 | 显示全部楼层
勤奋灌水,天天向上!
回复

使用道具 举报

avatar 流动532 | 2021-10-6 19:40:50 | 显示全部楼层
最近精神病院在打折,admin楼主去看看吧?
回复

使用道具 举报

avatar 123457567 | 2021-10-17 01:29:00 | 显示全部楼层
论坛人气好旺!
回复

使用道具 举报

avatar 天然悠然牌 | 2021-10-17 02:31:35 | 显示全部楼层
我回帖admin楼主给加积分吗?
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则