create_secret.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. /*
  2. Copyright 2015 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 cmd
  14. import (
  15. "fmt"
  16. "io"
  17. "github.com/renstrom/dedent"
  18. "github.com/spf13/cobra"
  19. "k8s.io/kubernetes/pkg/kubectl"
  20. cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  21. )
  22. // NewCmdCreateSecret groups subcommands to create various types of secrets
  23. func NewCmdCreateSecret(f *cmdutil.Factory, cmdOut io.Writer) *cobra.Command {
  24. cmd := &cobra.Command{
  25. Use: "secret",
  26. Short: "Create a secret using specified subcommand",
  27. Long: "Create a secret using specified subcommand.",
  28. Run: func(cmd *cobra.Command, args []string) {
  29. cmd.Help()
  30. },
  31. }
  32. cmd.AddCommand(NewCmdCreateSecretDockerRegistry(f, cmdOut))
  33. cmd.AddCommand(NewCmdCreateSecretTLS(f, cmdOut))
  34. cmd.AddCommand(NewCmdCreateSecretGeneric(f, cmdOut))
  35. return cmd
  36. }
  37. var (
  38. secretLong = dedent.Dedent(`
  39. Create a secret based on a file, directory, or specified literal value.
  40. A single secret may package one or more key/value pairs.
  41. When creating a secret based on a file, the key will default to the basename of the file, and the value will
  42. default to the file content. If the basename is an invalid key, you may specify an alternate key.
  43. When creating a secret based on a directory, each file whose basename is a valid key in the directory will be
  44. packaged into the secret. Any directory entries except regular files are ignored (e.g. subdirectories,
  45. symlinks, devices, pipes, etc).
  46. `)
  47. secretExample = dedent.Dedent(`
  48. # Create a new secret named my-secret with keys for each file in folder bar
  49. kubectl create secret generic my-secret --from-file=path/to/bar
  50. # Create a new secret named my-secret with specified keys instead of names on disk
  51. kubectl create secret generic my-secret --from-file=ssh-privatekey=~/.ssh/id_rsa --from-file=ssh-publickey=~/.ssh/id_rsa.pub
  52. # Create a new secret named my-secret with key1=supersecret and key2=topsecret
  53. kubectl create secret generic my-secret --from-literal=key1=supersecret --from-literal=key2=topsecret`)
  54. )
  55. // NewCmdCreateSecretGeneric is a command to create generic secrets from files, directories, or literal values
  56. func NewCmdCreateSecretGeneric(f *cmdutil.Factory, cmdOut io.Writer) *cobra.Command {
  57. cmd := &cobra.Command{
  58. Use: "generic NAME [--type=string] [--from-file=[key=]source] [--from-literal=key1=value1] [--dry-run]",
  59. Short: "Create a secret from a local file, directory or literal value",
  60. Long: secretLong,
  61. Example: secretExample,
  62. Run: func(cmd *cobra.Command, args []string) {
  63. err := CreateSecretGeneric(f, cmdOut, cmd, args)
  64. cmdutil.CheckErr(err)
  65. },
  66. }
  67. cmdutil.AddApplyAnnotationFlags(cmd)
  68. cmdutil.AddValidateFlags(cmd)
  69. cmdutil.AddPrinterFlags(cmd)
  70. cmdutil.AddGeneratorFlags(cmd, cmdutil.SecretV1GeneratorName)
  71. cmd.Flags().StringSlice("from-file", []string{}, "Key files can be specified using their file path, in which case a default name will be given to them, or optionally with a name and file path, in which case the given name will be used. Specifying a directory will iterate each named file in the directory that is a valid secret key.")
  72. cmd.Flags().StringSlice("from-literal", []string{}, "Specify a key and literal value to insert in secret (i.e. mykey=somevalue)")
  73. cmd.Flags().String("type", "", "The type of secret to create")
  74. return cmd
  75. }
  76. // CreateSecretGeneric is the implementation of the create secret generic command
  77. func CreateSecretGeneric(f *cmdutil.Factory, cmdOut io.Writer, cmd *cobra.Command, args []string) error {
  78. name, err := NameFromCommandArgs(cmd, args)
  79. if err != nil {
  80. return err
  81. }
  82. var generator kubectl.StructuredGenerator
  83. switch generatorName := cmdutil.GetFlagString(cmd, "generator"); generatorName {
  84. case cmdutil.SecretV1GeneratorName:
  85. generator = &kubectl.SecretGeneratorV1{
  86. Name: name,
  87. Type: cmdutil.GetFlagString(cmd, "type"),
  88. FileSources: cmdutil.GetFlagStringSlice(cmd, "from-file"),
  89. LiteralSources: cmdutil.GetFlagStringSlice(cmd, "from-literal"),
  90. }
  91. default:
  92. return cmdutil.UsageError(cmd, fmt.Sprintf("Generator: %s not supported.", generatorName))
  93. }
  94. return RunCreateSubcommand(f, cmd, cmdOut, &CreateSubcommandOptions{
  95. Name: name,
  96. StructuredGenerator: generator,
  97. DryRun: cmdutil.GetDryRunFlag(cmd),
  98. OutputFormat: cmdutil.GetFlagString(cmd, "output"),
  99. })
  100. }
  101. var (
  102. secretForDockerRegistryLong = dedent.Dedent(`
  103. Create a new secret for use with Docker registries.
  104. Dockercfg secrets are used to authenticate against Docker registries.
  105. When using the Docker command line to push images, you can authenticate to a given registry by running
  106. 'docker login DOCKER_REGISTRY_SERVER --username=DOCKER_USER --password=DOCKER_PASSWORD --email=DOCKER_EMAIL'.
  107. That produces a ~/.dockercfg file that is used by subsequent 'docker push' and 'docker pull' commands to
  108. authenticate to the registry.
  109. When creating applications, you may have a Docker registry that requires authentication. In order for the
  110. nodes to pull images on your behalf, they have to have the credentials. You can provide this information
  111. by creating a dockercfg secret and attaching it to your service account.`)
  112. secretForDockerRegistryExample = dedent.Dedent(`
  113. # If you don't already have a .dockercfg file, you can create a dockercfg secret directly by using:
  114. kubectl create secret docker-registry my-secret --docker-server=DOCKER_REGISTRY_SERVER --docker-username=DOCKER_USER --docker-password=DOCKER_PASSWORD --docker-email=DOCKER_EMAIL`)
  115. )
  116. // NewCmdCreateSecretDockerRegistry is a macro command for creating secrets to work with Docker registries
  117. func NewCmdCreateSecretDockerRegistry(f *cmdutil.Factory, cmdOut io.Writer) *cobra.Command {
  118. cmd := &cobra.Command{
  119. Use: "docker-registry NAME --docker-username=user --docker-password=password --docker-email=email [--docker-server=string] [--from-literal=key1=value1] [--dry-run]",
  120. Short: "Create a secret for use with a Docker registry",
  121. Long: secretForDockerRegistryLong,
  122. Example: secretForDockerRegistryExample,
  123. Run: func(cmd *cobra.Command, args []string) {
  124. err := CreateSecretDockerRegistry(f, cmdOut, cmd, args)
  125. cmdutil.CheckErr(err)
  126. },
  127. }
  128. cmdutil.AddApplyAnnotationFlags(cmd)
  129. cmdutil.AddValidateFlags(cmd)
  130. cmdutil.AddPrinterFlags(cmd)
  131. cmdutil.AddGeneratorFlags(cmd, cmdutil.SecretForDockerRegistryV1GeneratorName)
  132. cmd.Flags().String("docker-username", "", "Username for Docker registry authentication")
  133. cmd.MarkFlagRequired("docker-username")
  134. cmd.Flags().String("docker-password", "", "Password for Docker registry authentication")
  135. cmd.MarkFlagRequired("docker-password")
  136. cmd.Flags().String("docker-email", "", "Email for Docker registry")
  137. cmd.MarkFlagRequired("docker-email")
  138. cmd.Flags().String("docker-server", "https://index.docker.io/v1/", "Server location for Docker registry")
  139. cmdutil.AddInclude3rdPartyFlags(cmd)
  140. return cmd
  141. }
  142. // CreateSecretDockerRegistry is the implementation of the create secret docker-registry command
  143. func CreateSecretDockerRegistry(f *cmdutil.Factory, cmdOut io.Writer, cmd *cobra.Command, args []string) error {
  144. name, err := NameFromCommandArgs(cmd, args)
  145. if err != nil {
  146. return err
  147. }
  148. requiredFlags := []string{"docker-username", "docker-password", "docker-email", "docker-server"}
  149. for _, requiredFlag := range requiredFlags {
  150. if value := cmdutil.GetFlagString(cmd, requiredFlag); len(value) == 0 {
  151. return cmdutil.UsageError(cmd, "flag %s is required", requiredFlag)
  152. }
  153. }
  154. var generator kubectl.StructuredGenerator
  155. switch generatorName := cmdutil.GetFlagString(cmd, "generator"); generatorName {
  156. case cmdutil.SecretForDockerRegistryV1GeneratorName:
  157. generator = &kubectl.SecretForDockerRegistryGeneratorV1{
  158. Name: name,
  159. Username: cmdutil.GetFlagString(cmd, "docker-username"),
  160. Email: cmdutil.GetFlagString(cmd, "docker-email"),
  161. Password: cmdutil.GetFlagString(cmd, "docker-password"),
  162. Server: cmdutil.GetFlagString(cmd, "docker-server"),
  163. }
  164. default:
  165. return cmdutil.UsageError(cmd, fmt.Sprintf("Generator: %s not supported.", generatorName))
  166. }
  167. return RunCreateSubcommand(f, cmd, cmdOut, &CreateSubcommandOptions{
  168. Name: name,
  169. StructuredGenerator: generator,
  170. DryRun: cmdutil.GetDryRunFlag(cmd),
  171. OutputFormat: cmdutil.GetFlagString(cmd, "output"),
  172. })
  173. }
  174. var (
  175. secretForTLSLong = dedent.Dedent(`
  176. Create a TLS secret from the given public/private key pair.
  177. The public/private key pair must exist before hand. The public key certificate must be .PEM encoded and match the given private key.`)
  178. secretForTLSExample = dedent.Dedent(`
  179. # Create a new TLS secret named tls-secret with the given key pair:
  180. kubectl create secret tls tls-secret --cert=path/to/tls.cert --key=path/to/tls.key`)
  181. )
  182. // NewCmdCreateSecretTLS is a macro command for creating secrets to work with Docker registries
  183. func NewCmdCreateSecretTLS(f *cmdutil.Factory, cmdOut io.Writer) *cobra.Command {
  184. cmd := &cobra.Command{
  185. Use: "tls NAME --cert=path/to/cert/file --key=path/to/key/file [--dry-run]",
  186. Short: "Create a TLS secret",
  187. Long: secretForTLSLong,
  188. Example: secretForTLSExample,
  189. Run: func(cmd *cobra.Command, args []string) {
  190. err := CreateSecretTLS(f, cmdOut, cmd, args)
  191. cmdutil.CheckErr(err)
  192. },
  193. }
  194. cmdutil.AddApplyAnnotationFlags(cmd)
  195. cmdutil.AddValidateFlags(cmd)
  196. cmdutil.AddPrinterFlags(cmd)
  197. cmdutil.AddGeneratorFlags(cmd, cmdutil.SecretForTLSV1GeneratorName)
  198. cmd.Flags().String("cert", "", "Path to PEM encoded public key certificate.")
  199. cmd.Flags().String("key", "", "Path to private key associated with given certificate.")
  200. return cmd
  201. }
  202. // CreateSecretTLS is the implementation of the create secret tls command
  203. func CreateSecretTLS(f *cmdutil.Factory, cmdOut io.Writer, cmd *cobra.Command, args []string) error {
  204. name, err := NameFromCommandArgs(cmd, args)
  205. if err != nil {
  206. return err
  207. }
  208. requiredFlags := []string{"cert", "key"}
  209. for _, requiredFlag := range requiredFlags {
  210. if value := cmdutil.GetFlagString(cmd, requiredFlag); len(value) == 0 {
  211. return cmdutil.UsageError(cmd, "flag %s is required", requiredFlag)
  212. }
  213. }
  214. var generator kubectl.StructuredGenerator
  215. switch generatorName := cmdutil.GetFlagString(cmd, "generator"); generatorName {
  216. case cmdutil.SecretForTLSV1GeneratorName:
  217. generator = &kubectl.SecretForTLSGeneratorV1{
  218. Name: name,
  219. Key: cmdutil.GetFlagString(cmd, "key"),
  220. Cert: cmdutil.GetFlagString(cmd, "cert"),
  221. }
  222. default:
  223. return cmdutil.UsageError(cmd, fmt.Sprintf("Generator: %s not supported.", generatorName))
  224. }
  225. return RunCreateSubcommand(f, cmd, cmdOut, &CreateSubcommandOptions{
  226. Name: name,
  227. StructuredGenerator: generator,
  228. DryRun: cmdutil.GetFlagBool(cmd, "dry-run"),
  229. OutputFormat: cmdutil.GetFlagString(cmd, "output"),
  230. })
  231. }