context.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // +build kube
  2. /*
  3. Copyright 2020 Docker Compose CLI authors
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. package kubernetes
  15. import (
  16. "fmt"
  17. "os"
  18. "k8s.io/client-go/tools/clientcmd"
  19. )
  20. // ListAvailableKubeConfigContexts list kube contexts
  21. func ListAvailableKubeConfigContexts(kubeconfig string) ([]string, error) {
  22. config, err := clientcmd.NewDefaultPathOptions().GetStartingConfig()
  23. if err != nil {
  24. return nil, err
  25. }
  26. if kubeconfig != "" {
  27. f, err := os.Stat(kubeconfig)
  28. if os.IsNotExist(err) {
  29. return nil, err
  30. }
  31. if f.IsDir() {
  32. return nil, fmt.Errorf("%s not a config file", kubeconfig)
  33. }
  34. config = clientcmd.GetConfigFromFileOrDie(kubeconfig)
  35. }
  36. contexts := []string{}
  37. for k := range config.Contexts {
  38. contexts = append(contexts, k)
  39. }
  40. return contexts, nil
  41. }