create_kube.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // +build kube
  2. /*
  3. Copyright 2020 Docker Compose CLI authors
  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. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. package context
  15. import (
  16. "context"
  17. "github.com/pkg/errors"
  18. "github.com/spf13/cobra"
  19. "github.com/docker/compose-cli/api/context/store"
  20. "github.com/docker/compose-cli/api/errdefs"
  21. "github.com/docker/compose-cli/kube"
  22. )
  23. func init() {
  24. extraCommands = append(extraCommands, createKubeCommand)
  25. extraHelp = append(extraHelp, `
  26. Create a Kubernetes context:
  27. $ docker context create k8s CONTEXT [flags]
  28. (see docker context create k8s --help)
  29. `)
  30. }
  31. func createKubeCommand() *cobra.Command {
  32. var opts kube.ContextParams
  33. cmd := &cobra.Command{
  34. Use: "kubernetes CONTEXT [flags]",
  35. Short: "Create context for a Kubernetes Cluster",
  36. Args: cobra.ExactArgs(1),
  37. RunE: func(cmd *cobra.Command, args []string) error {
  38. return runCreateKube(cmd.Context(), args[0], opts)
  39. },
  40. }
  41. addDescriptionFlag(cmd, &opts.Description)
  42. cmd.Flags().StringVar(&opts.KubeConfigPath, "kubeconfig", "", "The endpoint of the Kubernetes manager")
  43. cmd.Flags().StringVar(&opts.KubeContextName, "kubecontext", "", "The name of the context to use in kubeconfig")
  44. cmd.Flags().BoolVar(&opts.FromEnvironment, "from-env", false, "Get endpoint and creds from env vars")
  45. return cmd
  46. }
  47. func runCreateKube(ctx context.Context, contextName string, opts kube.ContextParams) error {
  48. if contextExists(ctx, contextName) {
  49. return errors.Wrapf(errdefs.ErrAlreadyExists, "context %q", contextName)
  50. }
  51. contextData, description, err := opts.CreateContextData()
  52. if err != nil {
  53. return err
  54. }
  55. return createDockerContext(ctx, contextName, store.KubeContextType, description, contextData)
  56. }