create_cluster.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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/renstrom/dedent"
  21. "github.com/spf13/cobra"
  22. "k8s.io/kubernetes/pkg/client/unversioned/clientcmd"
  23. clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api"
  24. "k8s.io/kubernetes/pkg/util"
  25. "k8s.io/kubernetes/pkg/util/flag"
  26. )
  27. type createClusterOptions struct {
  28. configAccess clientcmd.ConfigAccess
  29. name string
  30. server util.StringFlag
  31. apiVersion util.StringFlag
  32. insecureSkipTLSVerify flag.Tristate
  33. certificateAuthority util.StringFlag
  34. embedCAData flag.Tristate
  35. }
  36. var (
  37. create_cluster_long = dedent.Dedent(`
  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. create_cluster_example = dedent.Dedent(`
  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. func NewCmdConfigSetCluster(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command {
  49. options := &createClusterOptions{configAccess: configAccess}
  50. cmd := &cobra.Command{
  51. Use: fmt.Sprintf("set-cluster NAME [--%v=server] [--%v=path/to/certificate/authority] [--%v=true]", clientcmd.FlagAPIServer, clientcmd.FlagCAFile, clientcmd.FlagInsecure),
  52. Short: "Sets a cluster entry in kubeconfig",
  53. Long: create_cluster_long,
  54. Example: create_cluster_example,
  55. Run: func(cmd *cobra.Command, args []string) {
  56. if !options.complete(cmd) {
  57. return
  58. }
  59. err := options.run()
  60. if err != nil {
  61. fmt.Fprintf(out, "%v\n", err)
  62. } else {
  63. fmt.Fprintf(out, "cluster %q set.\n", options.name)
  64. }
  65. },
  66. }
  67. options.insecureSkipTLSVerify.Default(false)
  68. cmd.Flags().Var(&options.server, clientcmd.FlagAPIServer, clientcmd.FlagAPIServer+" for the cluster entry in kubeconfig")
  69. cmd.Flags().Var(&options.apiVersion, clientcmd.FlagAPIVersion, clientcmd.FlagAPIVersion+" for the cluster entry in kubeconfig")
  70. f := cmd.Flags().VarPF(&options.insecureSkipTLSVerify, clientcmd.FlagInsecure, "", clientcmd.FlagInsecure+" for the cluster entry in kubeconfig")
  71. f.NoOptDefVal = "true"
  72. cmd.Flags().Var(&options.certificateAuthority, clientcmd.FlagCAFile, "path to "+clientcmd.FlagCAFile+" file for the cluster entry in kubeconfig")
  73. cmd.MarkFlagFilename(clientcmd.FlagCAFile)
  74. f = cmd.Flags().VarPF(&options.embedCAData, clientcmd.FlagEmbedCerts, "", clientcmd.FlagEmbedCerts+" for the cluster entry in kubeconfig")
  75. f.NoOptDefVal = "true"
  76. return cmd
  77. }
  78. func (o createClusterOptions) run() error {
  79. err := o.validate()
  80. if err != nil {
  81. return err
  82. }
  83. config, err := o.configAccess.GetStartingConfig()
  84. if err != nil {
  85. return err
  86. }
  87. startingStanza, exists := config.Clusters[o.name]
  88. if !exists {
  89. startingStanza = clientcmdapi.NewCluster()
  90. }
  91. cluster := o.modifyCluster(*startingStanza)
  92. config.Clusters[o.name] = &cluster
  93. if err := clientcmd.ModifyConfig(o.configAccess, *config, true); err != nil {
  94. return err
  95. }
  96. return nil
  97. }
  98. // cluster builds a Cluster object from the options
  99. func (o *createClusterOptions) modifyCluster(existingCluster clientcmdapi.Cluster) clientcmdapi.Cluster {
  100. modifiedCluster := existingCluster
  101. if o.server.Provided() {
  102. modifiedCluster.Server = o.server.Value()
  103. }
  104. if o.insecureSkipTLSVerify.Provided() {
  105. modifiedCluster.InsecureSkipTLSVerify = o.insecureSkipTLSVerify.Value()
  106. // Specifying insecure mode clears any certificate authority
  107. if modifiedCluster.InsecureSkipTLSVerify {
  108. modifiedCluster.CertificateAuthority = ""
  109. modifiedCluster.CertificateAuthorityData = nil
  110. }
  111. }
  112. if o.certificateAuthority.Provided() {
  113. caPath := o.certificateAuthority.Value()
  114. if o.embedCAData.Value() {
  115. modifiedCluster.CertificateAuthorityData, _ = ioutil.ReadFile(caPath)
  116. modifiedCluster.InsecureSkipTLSVerify = false
  117. modifiedCluster.CertificateAuthority = ""
  118. } else {
  119. caPath, _ = filepath.Abs(caPath)
  120. modifiedCluster.CertificateAuthority = caPath
  121. // Specifying a certificate authority file clears certificate authority data and insecure mode
  122. if caPath != "" {
  123. modifiedCluster.InsecureSkipTLSVerify = false
  124. modifiedCluster.CertificateAuthorityData = nil
  125. }
  126. }
  127. }
  128. return modifiedCluster
  129. }
  130. func (o *createClusterOptions) complete(cmd *cobra.Command) bool {
  131. args := cmd.Flags().Args()
  132. if len(args) != 1 {
  133. cmd.Help()
  134. return false
  135. }
  136. o.name = args[0]
  137. return true
  138. }
  139. func (o createClusterOptions) validate() error {
  140. if len(o.name) == 0 {
  141. return errors.New("you must specify a non-empty cluster name")
  142. }
  143. if o.insecureSkipTLSVerify.Value() && o.certificateAuthority.Value() != "" {
  144. return errors.New("you cannot specify a certificate authority and insecure mode at the same time")
  145. }
  146. if o.embedCAData.Value() {
  147. caPath := o.certificateAuthority.Value()
  148. if caPath == "" {
  149. return fmt.Errorf("you must specify a --%s to embed", clientcmd.FlagCAFile)
  150. }
  151. if _, err := ioutil.ReadFile(caPath); err != nil {
  152. return fmt.Errorf("could not read %s data from %s: %v", clientcmd.FlagCAFile, caPath, err)
  153. }
  154. }
  155. return nil
  156. }