loader.go 1.2 KB

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