generate.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package cmd
  2. import (
  3. "fmt"
  4. "path/filepath"
  5. "github.com/porter-dev/porter/internal/kubernetes/local"
  6. "k8s.io/client-go/tools/clientcmd"
  7. "k8s.io/client-go/util/homedir"
  8. "github.com/spf13/cobra"
  9. )
  10. var (
  11. outputFile string
  12. kubeconfigPath string
  13. print *bool
  14. contexts *[]string
  15. )
  16. // generateCmd represents the generate command
  17. var generateCmd = &cobra.Command{
  18. Use: "generate",
  19. Short: "Generates a kubeconfig with certificate data added",
  20. Run: func(cmd *cobra.Command, args []string) {
  21. generate(kubeconfigPath, outputFile, *print, *contexts)
  22. },
  23. }
  24. func init() {
  25. home := homedir.HomeDir()
  26. rootCmd.AddCommand(generateCmd)
  27. generateCmd.PersistentFlags().StringVarP(
  28. &outputFile,
  29. "output",
  30. "o",
  31. filepath.Join(home, ".porter", "porter.kubeconfig"),
  32. "output file location",
  33. )
  34. generateCmd.PersistentFlags().StringVarP(
  35. &kubeconfigPath,
  36. "kubeconfig",
  37. "k",
  38. "",
  39. "path to kubeconfig",
  40. )
  41. contexts = generateCmd.PersistentFlags().StringArray(
  42. "contexts",
  43. nil,
  44. "the list of contexts to use (defaults to the current context)",
  45. )
  46. print = generateCmd.PersistentFlags().BoolP(
  47. "print",
  48. "p",
  49. false,
  50. "print result to stdout, without writing to the fs",
  51. )
  52. }
  53. func generate(kubeconfigPath string, output string, print bool, contexts []string) error {
  54. conf, err := local.GetConfigFromHostWithCertData(kubeconfigPath, contexts)
  55. if err != nil {
  56. return err
  57. }
  58. rawConf, err := conf.RawConfig()
  59. if err != nil {
  60. return err
  61. }
  62. if print {
  63. bytes, err := clientcmd.Write(rawConf)
  64. if err != nil {
  65. return err
  66. }
  67. fmt.Printf(string(bytes))
  68. return nil
  69. }
  70. err = clientcmd.WriteToFile(rawConf, output)
  71. if err != nil {
  72. return err
  73. }
  74. return nil
  75. }