create_context.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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. "fmt"
  17. "io"
  18. "github.com/spf13/cobra"
  19. "k8s.io/client-go/tools/clientcmd"
  20. clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
  21. cliflag "k8s.io/component-base/cli/flag"
  22. cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  23. "k8s.io/kubernetes/pkg/kubectl/util/i18n"
  24. "k8s.io/kubernetes/pkg/kubectl/util/templates"
  25. )
  26. type createContextOptions struct {
  27. configAccess clientcmd.ConfigAccess
  28. name string
  29. currContext bool
  30. cluster cliflag.StringFlag
  31. authInfo cliflag.StringFlag
  32. namespace cliflag.StringFlag
  33. }
  34. var (
  35. createContextLong = templates.LongDesc(`
  36. Sets a context entry in kubeconfig
  37. Specifying a name that already exists will merge new fields on top of existing values for those fields.`)
  38. createContextExample = templates.Examples(`
  39. # Set the user field on the gce context entry without touching other values
  40. kubectl config set-context gce --user=cluster-admin`)
  41. )
  42. // NewCmdConfigSetContext returns a Command instance for 'config set-context' sub command
  43. func NewCmdConfigSetContext(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command {
  44. options := &createContextOptions{configAccess: configAccess}
  45. cmd := &cobra.Command{
  46. Use: fmt.Sprintf("set-context [NAME | --current] [--%v=cluster_nickname] [--%v=user_nickname] [--%v=namespace]", clientcmd.FlagClusterName, clientcmd.FlagAuthInfoName, clientcmd.FlagNamespace),
  47. DisableFlagsInUseLine: true,
  48. Short: i18n.T("Sets a context entry in kubeconfig"),
  49. Long: createContextLong,
  50. Example: createContextExample,
  51. Run: func(cmd *cobra.Command, args []string) {
  52. cmdutil.CheckErr(options.complete(cmd))
  53. name, exists, err := options.run()
  54. cmdutil.CheckErr(err)
  55. if exists {
  56. fmt.Fprintf(out, "Context %q modified.\n", name)
  57. } else {
  58. fmt.Fprintf(out, "Context %q created.\n", name)
  59. }
  60. },
  61. }
  62. cmd.Flags().BoolVar(&options.currContext, "current", options.currContext, "Modify the current context")
  63. cmd.Flags().Var(&options.cluster, clientcmd.FlagClusterName, clientcmd.FlagClusterName+" for the context entry in kubeconfig")
  64. cmd.Flags().Var(&options.authInfo, clientcmd.FlagAuthInfoName, clientcmd.FlagAuthInfoName+" for the context entry in kubeconfig")
  65. cmd.Flags().Var(&options.namespace, clientcmd.FlagNamespace, clientcmd.FlagNamespace+" for the context entry in kubeconfig")
  66. return cmd
  67. }
  68. func (o createContextOptions) run() (string, bool, error) {
  69. err := o.validate()
  70. if err != nil {
  71. return "", false, err
  72. }
  73. config, err := o.configAccess.GetStartingConfig()
  74. if err != nil {
  75. return "", false, err
  76. }
  77. name := o.name
  78. if o.currContext {
  79. if len(config.CurrentContext) == 0 {
  80. return "", false, errors.New("no current context is set")
  81. }
  82. name = config.CurrentContext
  83. }
  84. startingStanza, exists := config.Contexts[name]
  85. if !exists {
  86. startingStanza = clientcmdapi.NewContext()
  87. }
  88. context := o.modifyContext(*startingStanza)
  89. config.Contexts[name] = &context
  90. if err := clientcmd.ModifyConfig(o.configAccess, *config, true); err != nil {
  91. return name, exists, err
  92. }
  93. return name, exists, nil
  94. }
  95. func (o *createContextOptions) modifyContext(existingContext clientcmdapi.Context) clientcmdapi.Context {
  96. modifiedContext := existingContext
  97. if o.cluster.Provided() {
  98. modifiedContext.Cluster = o.cluster.Value()
  99. }
  100. if o.authInfo.Provided() {
  101. modifiedContext.AuthInfo = o.authInfo.Value()
  102. }
  103. if o.namespace.Provided() {
  104. modifiedContext.Namespace = o.namespace.Value()
  105. }
  106. return modifiedContext
  107. }
  108. func (o *createContextOptions) complete(cmd *cobra.Command) error {
  109. args := cmd.Flags().Args()
  110. if len(args) > 1 {
  111. return helpErrorf(cmd, "Unexpected args: %v", args)
  112. }
  113. if len(args) == 1 {
  114. o.name = args[0]
  115. }
  116. return nil
  117. }
  118. func (o createContextOptions) validate() error {
  119. if len(o.name) == 0 && !o.currContext {
  120. return errors.New("you must specify a non-empty context name or --current")
  121. }
  122. if len(o.name) > 0 && o.currContext {
  123. return errors.New("you cannot specify both a context name and --current")
  124. }
  125. return nil
  126. }