loader.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package kubeconfig
  2. import (
  3. "fmt"
  4. "k8s.io/client-go/kubernetes"
  5. _ "k8s.io/client-go/plugin/pkg/client/auth"
  6. "k8s.io/client-go/rest"
  7. "k8s.io/client-go/tools/clientcmd"
  8. )
  9. // LoadKubeconfig attempts to load a kubeconfig based on default locations.
  10. // If a path is passed in then only that path is checked and will error
  11. // if not found
  12. func LoadKubeconfig(path string) (*rest.Config, error) {
  13. // Use the default load order: KUBECONFIG env > $HOME/.kube/config > In cluster config
  14. loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
  15. if path != "" {
  16. loadingRules.ExplicitPath = path
  17. }
  18. loader := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, &clientcmd.ConfigOverrides{})
  19. config, err := loader.ClientConfig()
  20. if err != nil {
  21. return nil, fmt.Errorf("loading kubeconfig: %w", err)
  22. }
  23. config.UserAgent = "opencost"
  24. // use protobuf for faster serialization instead of default json
  25. // https://kubernetes.io/docs/reference/using-api/api-concepts/#alternate-representations-of-resources
  26. config.AcceptContentTypes = "application/vnd.kubernetes.protobuf,application/json"
  27. config.ContentType = "application/vnd.kubernetes.protobuf"
  28. return config, nil
  29. }
  30. // LoadKubeClient accepts a path to a kubeconfig to load and returns the clientset
  31. func LoadKubeClient(path string) (*kubernetes.Clientset, error) {
  32. config, err := LoadKubeconfig(path)
  33. if err != nil {
  34. return nil, err
  35. }
  36. return kubernetes.NewForConfig(config)
  37. }