如何在go中使用kubernetes的inclusterconfig

evrscar2  于 2022-11-02  发布在  Kubernetes
关注(0)|答案(1)|浏览(182)

我使用的是kubernetes-client。在这里,我尝试使用filepath来加载我的配置文件。我想使用inclusterconfig创建客户端,而不必加载kubeconfig文件。我该如何着手做呢?

  1. var kube_config_path = "/home/saivamsi/.kube/config"
  2. var config, conferr = clientcmd.BuildConfigFromFlags("", kube_config_path)
  3. var clientset, cler = kubernetes.NewForConfig(config)
t5fffqht

t5fffqht1#

这是一个example

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. "k8s.io/apimachinery/pkg/api/errors"
  7. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  8. "k8s.io/client-go/kubernetes"
  9. "k8s.io/client-go/rest"
  10. //
  11. // Uncomment to load all auth plugins
  12. // _ "k8s.io/client-go/plugin/pkg/client/auth"
  13. //
  14. // Or uncomment to load specific auth plugins
  15. // _ "k8s.io/client-go/plugin/pkg/client/auth/azure"
  16. // _ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
  17. // _ "k8s.io/client-go/plugin/pkg/client/auth/oidc"
  18. // _ "k8s.io/client-go/plugin/pkg/client/auth/openstack"
  19. )
  20. func main() {
  21. // creates the in-cluster config
  22. config, err := rest.InClusterConfig()
  23. if err != nil {
  24. panic(err.Error())
  25. }
  26. // creates the clientset
  27. clientset, err := kubernetes.NewForConfig(config)
  28. if err != nil {
  29. panic(err.Error())
  30. }
  31. for {
  32. // get pods in all the namespaces by omitting namespace
  33. // Or specify namespace to get pods in particular namespace
  34. pods, err := clientset.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{})
  35. if err != nil {
  36. panic(err.Error())
  37. }
  38. fmt.Printf("There are %d pods in the cluster\n", len(pods.Items))
  39. // Examples for error handling:
  40. // - Use helper functions e.g. errors.IsNotFound()
  41. // - And/or cast to StatusError and use its properties like e.g. ErrStatus.Message
  42. _, err = clientset.CoreV1().Pods("default").Get(context.TODO(), "example-xxxxx", metav1.GetOptions{})
  43. if errors.IsNotFound(err) {
  44. fmt.Printf("Pod example-xxxxx not found in default namespace\n")
  45. } else if statusError, isStatus := err.(*errors.StatusError); isStatus {
  46. fmt.Printf("Error getting pod %v\n", statusError.ErrStatus.Message)
  47. } else if err != nil {
  48. panic(err.Error())
  49. } else {
  50. fmt.Printf("Found example-xxxxx pod in default namespace\n")
  51. }
  52. time.Sleep(10 * time.Second)
  53. }
  54. }
展开查看全部

相关问题