generate.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. package cmd
  2. import (
  3. "fmt"
  4. "path/filepath"
  5. "github.com/porter-dev/porter/internal/kubernetes/local"
  6. "github.com/porter-dev/porter/internal/utils"
  7. gcpLocal "github.com/porter-dev/porter/internal/providers/gcp/local"
  8. "k8s.io/client-go/tools/clientcmd"
  9. "k8s.io/client-go/util/homedir"
  10. "github.com/spf13/cobra"
  11. )
  12. var (
  13. outputFile string
  14. kubeconfigPath string
  15. print *bool
  16. contexts *[]string
  17. )
  18. // generateCmd represents the generate command
  19. var generateCmd = &cobra.Command{
  20. Use: "generate",
  21. Short: "Generates a kubeconfig with certificate data added",
  22. Run: func(cmd *cobra.Command, args []string) {
  23. generate(kubeconfigPath, outputFile, *print, *contexts)
  24. },
  25. }
  26. func init() {
  27. home := homedir.HomeDir()
  28. rootCmd.AddCommand(generateCmd)
  29. generateCmd.PersistentFlags().StringVarP(
  30. &outputFile,
  31. "output",
  32. "o",
  33. filepath.Join(home, ".porter", "porter.kubeconfig"),
  34. "output file location",
  35. )
  36. generateCmd.PersistentFlags().StringVarP(
  37. &kubeconfigPath,
  38. "kubeconfig",
  39. "k",
  40. "",
  41. "path to kubeconfig",
  42. )
  43. contexts = generateCmd.PersistentFlags().StringArray(
  44. "contexts",
  45. nil,
  46. "the list of contexts to use (defaults to the current context)",
  47. )
  48. print = generateCmd.PersistentFlags().BoolP(
  49. "print",
  50. "p",
  51. false,
  52. "print result to stdout, without writing to the fs",
  53. )
  54. }
  55. func generate(kubeconfigPath string, output string, print bool, contexts []string) error {
  56. conf, err := local.GetConfigFromHostWithCertData(kubeconfigPath, contexts)
  57. if err != nil {
  58. return err
  59. }
  60. rawConf, err := conf.RawConfig()
  61. if err != nil {
  62. return err
  63. }
  64. if print {
  65. bytes, err := clientcmd.Write(rawConf)
  66. if err != nil {
  67. return err
  68. }
  69. fmt.Printf(string(bytes))
  70. return nil
  71. }
  72. err = clientcmd.WriteToFile(rawConf, output)
  73. if err != nil {
  74. return err
  75. }
  76. return nil
  77. }
  78. // TODO -- error handling, stop hard-coding, ask for permissions
  79. func gcpHelper() {
  80. agent, _ := gcpLocal.NewDefaultAgent()
  81. agent.ProjectID = "PROJECT_ID"
  82. name := "porter-dashboard-" + utils.StringWithCharset(6, "abcdefghijklmnopqrstuvwxyz1234567890")
  83. resp, err := agent.CreateServiceAccount(name)
  84. if err != nil {
  85. fmt.Printf("Error was %v\n", err)
  86. return
  87. }
  88. err = agent.SetServiceAccountIAMPolicy(resp)
  89. if err != nil {
  90. fmt.Printf("Error was %v\n", err)
  91. return
  92. }
  93. }