create_cluster.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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. "io/ioutil"
  19. "path/filepath"
  20. "github.com/spf13/cobra"
  21. "k8s.io/client-go/tools/clientcmd"
  22. clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
  23. cliflag "k8s.io/component-base/cli/flag"
  24. cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  25. "k8s.io/kubernetes/pkg/kubectl/util/i18n"
  26. "k8s.io/kubernetes/pkg/kubectl/util/templates"
  27. )
  28. type createClusterOptions struct {
  29. configAccess clientcmd.ConfigAccess
  30. name string
  31. server cliflag.StringFlag
  32. insecureSkipTLSVerify cliflag.Tristate
  33. certificateAuthority cliflag.StringFlag
  34. embedCAData cliflag.Tristate
  35. }
  36. var (
  37. createClusterLong = templates.LongDesc(`
  38. Sets a cluster entry in kubeconfig.
  39. Specifying a name that already exists will merge new fields on top of existing values for those fields.`)
  40. createClusterExample = templates.Examples(`
  41. # Set only the server field on the e2e cluster entry without touching other values.
  42. kubectl config set-cluster e2e --server=https://1.2.3.4
  43. # Embed certificate authority data for the e2e cluster entry
  44. kubectl config set-cluster e2e --certificate-authority=~/.kube/e2e/kubernetes.ca.crt
  45. # Disable cert checking for the dev cluster entry
  46. kubectl config set-cluster e2e --insecure-skip-tls-verify=true`)
  47. )
  48. // NewCmdConfigSetCluster returns a Command instance for 'config set-cluster' sub command
  49. func NewCmdConfigSetCluster(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command {
  50. options := &createClusterOptions{configAccess: configAccess}
  51. cmd := &cobra.Command{
  52. Use: fmt.Sprintf("set-cluster NAME [--%v=server] [--%v=path/to/certificate/authority] [--%v=true]", clientcmd.FlagAPIServer, clientcmd.FlagCAFile, clientcmd.FlagInsecure),
  53. DisableFlagsInUseLine: true,
  54. Short: i18n.T("Sets a cluster entry in kubeconfig"),
  55. Long: createClusterLong,
  56. Example: createClusterExample,
  57. Run: func(cmd *cobra.Command, args []string) {
  58. cmdutil.CheckErr(options.complete(cmd))
  59. cmdutil.CheckErr(options.run())
  60. fmt.Fprintf(out, "Cluster %q set.\n", options.name)
  61. },
  62. }
  63. options.insecureSkipTLSVerify.Default(false)
  64. cmd.Flags().Var(&options.server, clientcmd.FlagAPIServer, clientcmd.FlagAPIServer+" for the cluster entry in kubeconfig")
  65. f := cmd.Flags().VarPF(&options.insecureSkipTLSVerify, clientcmd.FlagInsecure, "", clientcmd.FlagInsecure+" for the cluster entry in kubeconfig")
  66. f.NoOptDefVal = "true"
  67. cmd.Flags().Var(&options.certificateAuthority, clientcmd.FlagCAFile, "Path to "+clientcmd.FlagCAFile+" file for the cluster entry in kubeconfig")
  68. cmd.MarkFlagFilename(clientcmd.FlagCAFile)
  69. f = cmd.Flags().VarPF(&options.embedCAData, clientcmd.FlagEmbedCerts, "", clientcmd.FlagEmbedCerts+" for the cluster entry in kubeconfig")
  70. f.NoOptDefVal = "true"
  71. return cmd
  72. }
  73. func (o createClusterOptions) run() error {
  74. err := o.validate()
  75. if err != nil {
  76. return err
  77. }
  78. config, err := o.configAccess.GetStartingConfig()
  79. if err != nil {
  80. return err
  81. }
  82. startingStanza, exists := config.Clusters[o.name]
  83. if !exists {
  84. startingStanza = clientcmdapi.NewCluster()
  85. }
  86. cluster := o.modifyCluster(*startingStanza)
  87. config.Clusters[o.name] = &cluster
  88. if err := clientcmd.ModifyConfig(o.configAccess, *config, true); err != nil {
  89. return err
  90. }
  91. return nil
  92. }
  93. // cluster builds a Cluster object from the options
  94. func (o *createClusterOptions) modifyCluster(existingCluster clientcmdapi.Cluster) clientcmdapi.Cluster {
  95. modifiedCluster := existingCluster
  96. if o.server.Provided() {
  97. modifiedCluster.Server = o.server.Value()
  98. }
  99. if o.insecureSkipTLSVerify.Provided() {
  100. modifiedCluster.InsecureSkipTLSVerify = o.insecureSkipTLSVerify.Value()
  101. // Specifying insecure mode clears any certificate authority
  102. if modifiedCluster.InsecureSkipTLSVerify {
  103. modifiedCluster.CertificateAuthority = ""
  104. modifiedCluster.CertificateAuthorityData = nil
  105. }
  106. }
  107. if o.certificateAuthority.Provided() {
  108. caPath := o.certificateAuthority.Value()
  109. if o.embedCAData.Value() {
  110. modifiedCluster.CertificateAuthorityData, _ = ioutil.ReadFile(caPath)
  111. modifiedCluster.InsecureSkipTLSVerify = false
  112. modifiedCluster.CertificateAuthority = ""
  113. } else {
  114. caPath, _ = filepath.Abs(caPath)
  115. modifiedCluster.CertificateAuthority = caPath
  116. // Specifying a certificate authority file clears certificate authority data and insecure mode
  117. if caPath != "" {
  118. modifiedCluster.InsecureSkipTLSVerify = false
  119. modifiedCluster.CertificateAuthorityData = nil
  120. }
  121. }
  122. }
  123. return modifiedCluster
  124. }
  125. func (o *createClusterOptions) complete(cmd *cobra.Command) error {
  126. args := cmd.Flags().Args()
  127. if len(args) != 1 {
  128. return helpErrorf(cmd, "Unexpected args: %v", args)
  129. }
  130. o.name = args[0]
  131. return nil
  132. }
  133. func (o createClusterOptions) validate() error {
  134. if len(o.name) == 0 {
  135. return errors.New("you must specify a non-empty cluster name")
  136. }
  137. if o.insecureSkipTLSVerify.Value() && o.certificateAuthority.Value() != "" {
  138. return errors.New("you cannot specify a certificate authority and insecure mode at the same time")
  139. }
  140. if o.embedCAData.Value() {
  141. caPath := o.certificateAuthority.Value()
  142. if caPath == "" {
  143. return fmt.Errorf("you must specify a --%s to embed", clientcmd.FlagCAFile)
  144. }
  145. if _, err := ioutil.ReadFile(caPath); err != nil {
  146. return fmt.Errorf("could not read %s data from %s: %v", clientcmd.FlagCAFile, caPath, err)
  147. }
  148. }
  149. return nil
  150. }