get_contexts.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. /*
  2. Copyright 2016 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package config
  14. import (
  15. "fmt"
  16. "io"
  17. "strings"
  18. "text/tabwriter"
  19. "github.com/spf13/cobra"
  20. "k8s.io/kubernetes/pkg/client/unversioned/clientcmd"
  21. clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api"
  22. "k8s.io/kubernetes/pkg/kubectl"
  23. cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  24. utilerrors "k8s.io/kubernetes/pkg/util/errors"
  25. "k8s.io/kubernetes/pkg/util/sets"
  26. )
  27. // GetContextsOptions contains the assignable options from the args.
  28. type GetContextsOptions struct {
  29. configAccess clientcmd.ConfigAccess
  30. nameOnly bool
  31. showHeaders bool
  32. contextNames []string
  33. out io.Writer
  34. }
  35. const (
  36. getContextsLong = `Displays one or many contexts from the kubeconfig file.`
  37. getContextsExample = `# List all the contexts in your kubeconfig file
  38. kubectl config get-contexts
  39. # Describe one context in your kubeconfig file.
  40. kubectl config get-contexts my-context`
  41. )
  42. // NewCmdConfigGetContexts creates a command object for the "get-contexts" action, which
  43. // retrieves one or more contexts from a kubeconfig.
  44. func NewCmdConfigGetContexts(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command {
  45. options := &GetContextsOptions{configAccess: configAccess}
  46. cmd := &cobra.Command{
  47. Use: "get-contexts [(-o|--output=)name)]",
  48. Short: "Describe one or many contexts",
  49. Long: getContextsLong,
  50. Example: getContextsExample,
  51. Run: func(cmd *cobra.Command, args []string) {
  52. validOutputTypes := sets.NewString("", "json", "yaml", "wide", "name", "custom-columns", "custom-columns-file", "go-template", "go-template-file", "jsonpath", "jsonpath-file")
  53. supportedOutputTypes := sets.NewString("", "name")
  54. outputFormat := cmdutil.GetFlagString(cmd, "output")
  55. if !validOutputTypes.Has(outputFormat) {
  56. cmdutil.CheckErr(fmt.Errorf("output must be one of '' or 'name': %v", outputFormat))
  57. }
  58. if !supportedOutputTypes.Has(outputFormat) {
  59. fmt.Fprintf(out, "--output %v is not available in kubectl config get-contexts; resetting to default output format\n", outputFormat)
  60. cmd.Flags().Set("output", "")
  61. }
  62. cmdutil.CheckErr(options.Complete(cmd, args, out))
  63. cmdutil.CheckErr(options.RunGetContexts())
  64. },
  65. }
  66. cmdutil.AddOutputFlags(cmd)
  67. cmdutil.AddNoHeadersFlags(cmd)
  68. return cmd
  69. }
  70. // Complete assigns GetContextsOptions from the args.
  71. func (o *GetContextsOptions) Complete(cmd *cobra.Command, args []string, out io.Writer) error {
  72. o.contextNames = args
  73. o.out = out
  74. o.nameOnly = false
  75. if cmdutil.GetFlagString(cmd, "output") == "name" {
  76. o.nameOnly = true
  77. }
  78. o.showHeaders = true
  79. if cmdutil.GetFlagBool(cmd, "no-headers") || o.nameOnly {
  80. o.showHeaders = false
  81. }
  82. return nil
  83. }
  84. // RunGetContexts implements all the necessary functionality for context retrieval.
  85. func (o GetContextsOptions) RunGetContexts() error {
  86. config, err := o.configAccess.GetStartingConfig()
  87. if err != nil {
  88. return err
  89. }
  90. out, found := o.out.(*tabwriter.Writer)
  91. if !found {
  92. out = kubectl.GetNewTabWriter(o.out)
  93. defer out.Flush()
  94. }
  95. // Build a list of context names to print, and warn if any requested contexts are not found.
  96. // Do this before printing the headers so it doesn't look ugly.
  97. allErrs := []error{}
  98. toPrint := []string{}
  99. if len(o.contextNames) == 0 {
  100. for name := range config.Contexts {
  101. toPrint = append(toPrint, name)
  102. }
  103. } else {
  104. for _, name := range o.contextNames {
  105. _, ok := config.Contexts[name]
  106. if ok {
  107. toPrint = append(toPrint, name)
  108. } else {
  109. allErrs = append(allErrs, fmt.Errorf("context %v not found", name))
  110. }
  111. }
  112. }
  113. if o.showHeaders {
  114. err = printContextHeaders(out, o.nameOnly)
  115. if err != nil {
  116. allErrs = append(allErrs, err)
  117. }
  118. }
  119. for _, name := range toPrint {
  120. err = printContext(name, config.Contexts[name], out, o.nameOnly, config.CurrentContext == name)
  121. if err != nil {
  122. allErrs = append(allErrs, err)
  123. }
  124. }
  125. return utilerrors.NewAggregate(allErrs)
  126. }
  127. func printContextHeaders(out io.Writer, nameOnly bool) error {
  128. columnNames := []string{"CURRENT", "NAME", "CLUSTER", "AUTHINFO", "NAMESPACE"}
  129. if nameOnly {
  130. columnNames = columnNames[:1]
  131. }
  132. _, err := fmt.Fprintf(out, "%s\n", strings.Join(columnNames, "\t"))
  133. return err
  134. }
  135. func printContext(name string, context *clientcmdapi.Context, w io.Writer, nameOnly, current bool) error {
  136. if nameOnly {
  137. _, err := fmt.Fprintf(w, "%s\n", name)
  138. return err
  139. }
  140. prefix := " "
  141. if current {
  142. prefix = "*"
  143. }
  144. _, err := fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", prefix, name, context.Cluster, context.AuthInfo, context.Namespace)
  145. return err
  146. }