view.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. /*
  2. Copyright 2014 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. "errors"
  16. "github.com/spf13/cobra"
  17. "k8s.io/cli-runtime/pkg/genericclioptions"
  18. "k8s.io/cli-runtime/pkg/printers"
  19. "k8s.io/client-go/tools/clientcmd"
  20. clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
  21. "k8s.io/client-go/tools/clientcmd/api/latest"
  22. cliflag "k8s.io/component-base/cli/flag"
  23. cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  24. "k8s.io/kubernetes/pkg/kubectl/scheme"
  25. "k8s.io/kubernetes/pkg/kubectl/util/i18n"
  26. "k8s.io/kubernetes/pkg/kubectl/util/templates"
  27. )
  28. // ViewOptions holds the command-line options for 'config view' sub command
  29. type ViewOptions struct {
  30. PrintFlags *genericclioptions.PrintFlags
  31. PrintObject printers.ResourcePrinterFunc
  32. ConfigAccess clientcmd.ConfigAccess
  33. Merge cliflag.Tristate
  34. Flatten bool
  35. Minify bool
  36. RawByteData bool
  37. Context string
  38. OutputFormat string
  39. genericclioptions.IOStreams
  40. }
  41. var (
  42. viewLong = templates.LongDesc(`
  43. Display merged kubeconfig settings or a specified kubeconfig file.
  44. You can use --output jsonpath={...} to extract specific values using a jsonpath expression.`)
  45. viewExample = templates.Examples(`
  46. # Show merged kubeconfig settings.
  47. kubectl config view
  48. # Show merged kubeconfig settings and raw certificate data.
  49. kubectl config view --raw
  50. # Get the password for the e2e user
  51. kubectl config view -o jsonpath='{.users[?(@.name == "e2e")].user.password}'`)
  52. defaultOutputFormat = "yaml"
  53. )
  54. // NewCmdConfigView returns a Command instance for 'config view' sub command
  55. func NewCmdConfigView(f cmdutil.Factory, streams genericclioptions.IOStreams, ConfigAccess clientcmd.ConfigAccess) *cobra.Command {
  56. o := &ViewOptions{
  57. PrintFlags: genericclioptions.NewPrintFlags("").WithTypeSetter(scheme.Scheme).WithDefaultOutput("yaml"),
  58. ConfigAccess: ConfigAccess,
  59. IOStreams: streams,
  60. }
  61. cmd := &cobra.Command{
  62. Use: "view",
  63. Short: i18n.T("Display merged kubeconfig settings or a specified kubeconfig file"),
  64. Long: viewLong,
  65. Example: viewExample,
  66. Run: func(cmd *cobra.Command, args []string) {
  67. cmdutil.CheckErr(o.Complete(cmd, args))
  68. cmdutil.CheckErr(o.Validate())
  69. cmdutil.CheckErr(o.Run())
  70. },
  71. }
  72. o.PrintFlags.AddFlags(cmd)
  73. o.Merge.Default(true)
  74. mergeFlag := cmd.Flags().VarPF(&o.Merge, "merge", "", "Merge the full hierarchy of kubeconfig files")
  75. mergeFlag.NoOptDefVal = "true"
  76. cmd.Flags().BoolVar(&o.RawByteData, "raw", o.RawByteData, "Display raw byte data")
  77. cmd.Flags().BoolVar(&o.Flatten, "flatten", o.Flatten, "Flatten the resulting kubeconfig file into self-contained output (useful for creating portable kubeconfig files)")
  78. cmd.Flags().BoolVar(&o.Minify, "minify", o.Minify, "Remove all information not used by current-context from the output")
  79. return cmd
  80. }
  81. // Complete completes the required command-line options
  82. func (o *ViewOptions) Complete(cmd *cobra.Command, args []string) error {
  83. if len(args) != 0 {
  84. return cmdutil.UsageErrorf(cmd, "unexpected arguments: %v", args)
  85. }
  86. if o.ConfigAccess.IsExplicitFile() {
  87. if !o.Merge.Provided() {
  88. o.Merge.Set("false")
  89. }
  90. }
  91. printer, err := o.PrintFlags.ToPrinter()
  92. if err != nil {
  93. return err
  94. }
  95. o.PrintObject = printer.PrintObj
  96. o.Context = cmdutil.GetFlagString(cmd, "context")
  97. return nil
  98. }
  99. // Validate makes sure that provided values for command-line options are valid
  100. func (o ViewOptions) Validate() error {
  101. if !o.Merge.Value() && !o.ConfigAccess.IsExplicitFile() {
  102. return errors.New("if merge==false a precise file must to specified")
  103. }
  104. return nil
  105. }
  106. // Run performs the execution of 'config view' sub command
  107. func (o ViewOptions) Run() error {
  108. config, err := o.loadConfig()
  109. if err != nil {
  110. return err
  111. }
  112. if o.Minify {
  113. if len(o.Context) > 0 {
  114. config.CurrentContext = o.Context
  115. }
  116. if err := clientcmdapi.MinifyConfig(config); err != nil {
  117. return err
  118. }
  119. }
  120. if o.Flatten {
  121. if err := clientcmdapi.FlattenConfig(config); err != nil {
  122. return err
  123. }
  124. } else if !o.RawByteData {
  125. clientcmdapi.ShortenConfig(config)
  126. }
  127. convertedObj, err := latest.Scheme.ConvertToVersion(config, latest.ExternalVersion)
  128. if err != nil {
  129. return err
  130. }
  131. return o.PrintObject(convertedObj, o.Out)
  132. }
  133. func (o ViewOptions) loadConfig() (*clientcmdapi.Config, error) {
  134. err := o.Validate()
  135. if err != nil {
  136. return nil, err
  137. }
  138. config, err := o.getStartingConfig()
  139. return config, err
  140. }
  141. // getStartingConfig returns the Config object built from the sources specified by the options, the filename read (only if it was a single file), and an error if something goes wrong
  142. func (o *ViewOptions) getStartingConfig() (*clientcmdapi.Config, error) {
  143. switch {
  144. case !o.Merge.Value():
  145. return clientcmd.LoadFromFile(o.ConfigAccess.GetExplicitFile())
  146. default:
  147. return o.ConfigAccess.GetStartingConfig()
  148. }
  149. }