...

Source file src/k8s.io/kubectl/pkg/cmd/config/view.go

Documentation: k8s.io/kubectl/pkg/cmd/config

     1  /*
     2  Copyright 2014 The Kubernetes Authors.
     3  
     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  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package config
    18  
    19  import (
    20  	"errors"
    21  
    22  	"github.com/spf13/cobra"
    23  
    24  	"k8s.io/cli-runtime/pkg/genericclioptions"
    25  	"k8s.io/cli-runtime/pkg/genericiooptions"
    26  	"k8s.io/cli-runtime/pkg/printers"
    27  	"k8s.io/client-go/tools/clientcmd"
    28  	clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
    29  	"k8s.io/client-go/tools/clientcmd/api/latest"
    30  	cliflag "k8s.io/component-base/cli/flag"
    31  	cmdutil "k8s.io/kubectl/pkg/cmd/util"
    32  	"k8s.io/kubectl/pkg/scheme"
    33  	"k8s.io/kubectl/pkg/util/i18n"
    34  	"k8s.io/kubectl/pkg/util/templates"
    35  )
    36  
    37  // ViewOptions holds the command-line options for 'config view' sub command
    38  type ViewOptions struct {
    39  	PrintFlags  *genericclioptions.PrintFlags
    40  	PrintObject printers.ResourcePrinterFunc
    41  
    42  	ConfigAccess clientcmd.ConfigAccess
    43  	Merge        cliflag.Tristate
    44  	Flatten      bool
    45  	Minify       bool
    46  	RawByteData  bool
    47  
    48  	Context      string
    49  	OutputFormat string
    50  
    51  	genericiooptions.IOStreams
    52  }
    53  
    54  var (
    55  	viewLong = templates.LongDesc(i18n.T(`
    56  		Display merged kubeconfig settings or a specified kubeconfig file.
    57  
    58  		You can use --output jsonpath={...} to extract specific values using a jsonpath expression.`))
    59  
    60  	viewExample = templates.Examples(`
    61  		# Show merged kubeconfig settings
    62  		kubectl config view
    63  
    64  		# Show merged kubeconfig settings, raw certificate data, and exposed secrets
    65  		kubectl config view --raw
    66  
    67  		# Get the password for the e2e user
    68  		kubectl config view -o jsonpath='{.users[?(@.name == "e2e")].user.password}'`)
    69  )
    70  
    71  // NewCmdConfigView returns a Command instance for 'config view' sub command
    72  func NewCmdConfigView(streams genericiooptions.IOStreams, ConfigAccess clientcmd.ConfigAccess) *cobra.Command {
    73  	o := &ViewOptions{
    74  		PrintFlags:   genericclioptions.NewPrintFlags("").WithTypeSetter(scheme.Scheme).WithDefaultOutput("yaml"),
    75  		ConfigAccess: ConfigAccess,
    76  
    77  		IOStreams: streams,
    78  	}
    79  
    80  	cmd := &cobra.Command{
    81  		Use:     "view",
    82  		Short:   i18n.T("Display merged kubeconfig settings or a specified kubeconfig file"),
    83  		Long:    viewLong,
    84  		Example: viewExample,
    85  		Run: func(cmd *cobra.Command, args []string) {
    86  			cmdutil.CheckErr(o.Complete(cmd, args))
    87  			cmdutil.CheckErr(o.Validate())
    88  			cmdutil.CheckErr(o.Run())
    89  		},
    90  	}
    91  
    92  	o.PrintFlags.AddFlags(cmd)
    93  
    94  	o.Merge.Default(true)
    95  	mergeFlag := cmd.Flags().VarPF(&o.Merge, "merge", "", "Merge the full hierarchy of kubeconfig files")
    96  	mergeFlag.NoOptDefVal = "true"
    97  	cmd.Flags().BoolVar(&o.RawByteData, "raw", o.RawByteData, "Display raw byte data and sensitive data")
    98  	cmd.Flags().BoolVar(&o.Flatten, "flatten", o.Flatten, "Flatten the resulting kubeconfig file into self-contained output (useful for creating portable kubeconfig files)")
    99  	cmd.Flags().BoolVar(&o.Minify, "minify", o.Minify, "Remove all information not used by current-context from the output")
   100  	return cmd
   101  }
   102  
   103  // Complete completes the required command-line options
   104  func (o *ViewOptions) Complete(cmd *cobra.Command, args []string) error {
   105  	if len(args) != 0 {
   106  		return cmdutil.UsageErrorf(cmd, "unexpected arguments: %v", args)
   107  	}
   108  	if o.ConfigAccess.IsExplicitFile() {
   109  		if !o.Merge.Provided() {
   110  			o.Merge.Set("false")
   111  		}
   112  	}
   113  
   114  	printer, err := o.PrintFlags.ToPrinter()
   115  	if err != nil {
   116  		return err
   117  	}
   118  	o.PrintObject = printer.PrintObj
   119  	o.Context = cmdutil.GetFlagString(cmd, "context")
   120  
   121  	return nil
   122  }
   123  
   124  // Validate makes sure that provided values for command-line options are valid
   125  func (o ViewOptions) Validate() error {
   126  	if !o.Merge.Value() && !o.ConfigAccess.IsExplicitFile() {
   127  		return errors.New("if merge==false a precise file must be specified")
   128  	}
   129  
   130  	return nil
   131  }
   132  
   133  // Run performs the execution of 'config view' sub command
   134  func (o ViewOptions) Run() error {
   135  	config, err := o.loadConfig()
   136  	if err != nil {
   137  		return err
   138  	}
   139  
   140  	if o.Minify {
   141  		if len(o.Context) > 0 {
   142  			config.CurrentContext = o.Context
   143  		}
   144  		if err := clientcmdapi.MinifyConfig(config); err != nil {
   145  			return err
   146  		}
   147  	}
   148  
   149  	if o.Flatten {
   150  		if err := clientcmdapi.FlattenConfig(config); err != nil {
   151  			return err
   152  		}
   153  	} else if !o.RawByteData {
   154  		if err := clientcmdapi.RedactSecrets(config); err != nil {
   155  			return err
   156  		}
   157  		clientcmdapi.ShortenConfig(config)
   158  	}
   159  
   160  	convertedObj, err := latest.Scheme.ConvertToVersion(config, latest.ExternalVersion)
   161  	if err != nil {
   162  		return err
   163  	}
   164  
   165  	return o.PrintObject(convertedObj, o.Out)
   166  }
   167  
   168  func (o ViewOptions) loadConfig() (*clientcmdapi.Config, error) {
   169  	err := o.Validate()
   170  	if err != nil {
   171  		return nil, err
   172  	}
   173  
   174  	config, err := o.getStartingConfig()
   175  	return config, err
   176  }
   177  
   178  // 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
   179  func (o *ViewOptions) getStartingConfig() (*clientcmdapi.Config, error) {
   180  	switch {
   181  	case !o.Merge.Value():
   182  		return clientcmd.LoadFromFile(o.ConfigAccess.GetExplicitFile())
   183  
   184  	default:
   185  		return o.ConfigAccess.GetStartingConfig()
   186  	}
   187  }
   188  

View as plain text