get_contexts.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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. "sort"
  18. "strings"
  19. "github.com/liggitt/tabwriter"
  20. "github.com/spf13/cobra"
  21. utilerrors "k8s.io/apimachinery/pkg/util/errors"
  22. "k8s.io/apimachinery/pkg/util/sets"
  23. "k8s.io/cli-runtime/pkg/genericclioptions"
  24. "k8s.io/client-go/tools/clientcmd"
  25. clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
  26. cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  27. "k8s.io/kubernetes/pkg/kubectl/util/i18n"
  28. "k8s.io/kubernetes/pkg/kubectl/util/printers"
  29. "k8s.io/kubernetes/pkg/kubectl/util/templates"
  30. )
  31. // GetContextsOptions contains the assignable options from the args.
  32. type GetContextsOptions struct {
  33. configAccess clientcmd.ConfigAccess
  34. nameOnly bool
  35. showHeaders bool
  36. contextNames []string
  37. genericclioptions.IOStreams
  38. }
  39. var (
  40. getContextsLong = templates.LongDesc(`Displays one or many contexts from the kubeconfig file.`)
  41. getContextsExample = templates.Examples(`
  42. # List all the contexts in your kubeconfig file
  43. kubectl config get-contexts
  44. # Describe one context in your kubeconfig file.
  45. kubectl config get-contexts my-context`)
  46. )
  47. // NewCmdConfigGetContexts creates a command object for the "get-contexts" action, which
  48. // retrieves one or more contexts from a kubeconfig.
  49. func NewCmdConfigGetContexts(streams genericclioptions.IOStreams, configAccess clientcmd.ConfigAccess) *cobra.Command {
  50. options := &GetContextsOptions{
  51. configAccess: configAccess,
  52. IOStreams: streams,
  53. }
  54. cmd := &cobra.Command{
  55. Use: "get-contexts [(-o|--output=)name)]",
  56. DisableFlagsInUseLine: true,
  57. Short: i18n.T("Describe one or many contexts"),
  58. Long: getContextsLong,
  59. Example: getContextsExample,
  60. Run: func(cmd *cobra.Command, args []string) {
  61. validOutputTypes := sets.NewString("", "json", "yaml", "wide", "name", "custom-columns", "custom-columns-file", "go-template", "go-template-file", "jsonpath", "jsonpath-file")
  62. supportedOutputTypes := sets.NewString("", "name")
  63. outputFormat := cmdutil.GetFlagString(cmd, "output")
  64. if !validOutputTypes.Has(outputFormat) {
  65. cmdutil.CheckErr(fmt.Errorf("output must be one of '' or 'name': %v", outputFormat))
  66. }
  67. if !supportedOutputTypes.Has(outputFormat) {
  68. fmt.Fprintf(options.Out, "--output %v is not available in kubectl config get-contexts; resetting to default output format\n", outputFormat)
  69. cmd.Flags().Set("output", "")
  70. }
  71. cmdutil.CheckErr(options.Complete(cmd, args))
  72. cmdutil.CheckErr(options.RunGetContexts())
  73. },
  74. }
  75. cmd.Flags().Bool("no-headers", false, "When using the default or custom-column output format, don't print headers (default print headers).")
  76. cmd.Flags().StringP("output", "o", "", "Output format. One of: name")
  77. return cmd
  78. }
  79. // Complete assigns GetContextsOptions from the args.
  80. func (o *GetContextsOptions) Complete(cmd *cobra.Command, args []string) error {
  81. o.contextNames = args
  82. o.nameOnly = false
  83. if cmdutil.GetFlagString(cmd, "output") == "name" {
  84. o.nameOnly = true
  85. }
  86. o.showHeaders = true
  87. if cmdutil.GetFlagBool(cmd, "no-headers") || o.nameOnly {
  88. o.showHeaders = false
  89. }
  90. return nil
  91. }
  92. // RunGetContexts implements all the necessary functionality for context retrieval.
  93. func (o GetContextsOptions) RunGetContexts() error {
  94. config, err := o.configAccess.GetStartingConfig()
  95. if err != nil {
  96. return err
  97. }
  98. out, found := o.Out.(*tabwriter.Writer)
  99. if !found {
  100. out = printers.GetNewTabWriter(o.Out)
  101. defer out.Flush()
  102. }
  103. // Build a list of context names to print, and warn if any requested contexts are not found.
  104. // Do this before printing the headers so it doesn't look ugly.
  105. allErrs := []error{}
  106. toPrint := []string{}
  107. if len(o.contextNames) == 0 {
  108. for name := range config.Contexts {
  109. toPrint = append(toPrint, name)
  110. }
  111. } else {
  112. for _, name := range o.contextNames {
  113. _, ok := config.Contexts[name]
  114. if ok {
  115. toPrint = append(toPrint, name)
  116. } else {
  117. allErrs = append(allErrs, fmt.Errorf("context %v not found", name))
  118. }
  119. }
  120. }
  121. if o.showHeaders {
  122. err = printContextHeaders(out, o.nameOnly)
  123. if err != nil {
  124. allErrs = append(allErrs, err)
  125. }
  126. }
  127. sort.Strings(toPrint)
  128. for _, name := range toPrint {
  129. err = printContext(name, config.Contexts[name], out, o.nameOnly, config.CurrentContext == name)
  130. if err != nil {
  131. allErrs = append(allErrs, err)
  132. }
  133. }
  134. return utilerrors.NewAggregate(allErrs)
  135. }
  136. func printContextHeaders(out io.Writer, nameOnly bool) error {
  137. columnNames := []string{"CURRENT", "NAME", "CLUSTER", "AUTHINFO", "NAMESPACE"}
  138. if nameOnly {
  139. columnNames = columnNames[:1]
  140. }
  141. _, err := fmt.Fprintf(out, "%s\n", strings.Join(columnNames, "\t"))
  142. return err
  143. }
  144. func printContext(name string, context *clientcmdapi.Context, w io.Writer, nameOnly, current bool) error {
  145. if nameOnly {
  146. _, err := fmt.Fprintf(w, "%s\n", name)
  147. return err
  148. }
  149. prefix := " "
  150. if current {
  151. prefix = "*"
  152. }
  153. _, err := fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", prefix, name, context.Cluster, context.AuthInfo, context.Namespace)
  154. return err
  155. }