kubectl.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package cmd
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "os/exec"
  7. api "github.com/porter-dev/porter/api/client"
  8. "github.com/porter-dev/porter/api/types"
  9. "github.com/spf13/cobra"
  10. )
  11. var kubectlCmd = &cobra.Command{
  12. Use: "kubectl",
  13. Short: "Use kubectl to interact with a Porter cluster",
  14. Run: func(cmd *cobra.Command, args []string) {
  15. err := checkLoginAndRun(args, runKubectl)
  16. if err != nil {
  17. os.Exit(1)
  18. }
  19. },
  20. }
  21. func init() {
  22. rootCmd.AddCommand(kubectlCmd)
  23. }
  24. func runKubectl(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  25. _, err := exec.LookPath("kubectl")
  26. if err != nil {
  27. return fmt.Errorf("error finding kubectl: %w", err)
  28. }
  29. tmpFile, err := downloadTempKubeconfig(client)
  30. if err != nil {
  31. return err
  32. }
  33. defer func() {
  34. os.Remove(tmpFile)
  35. }()
  36. os.Setenv("KUBECONFIG", tmpFile)
  37. cmd := exec.Command("kubectl", args...)
  38. cmd.Stdout = os.Stdout
  39. cmd.Stderr = os.Stderr
  40. err = cmd.Run()
  41. if err != nil {
  42. return fmt.Errorf("error running helm: %w", err)
  43. }
  44. return nil
  45. }
  46. func downloadTempKubeconfig(client *api.Client) (string, error) {
  47. tmpFile, err := os.CreateTemp("", "porter_kubeconfig_*.yaml")
  48. if err != nil {
  49. return "", fmt.Errorf("error creating temp file for kubeconfig: %w", err)
  50. }
  51. defer tmpFile.Close()
  52. resp, err := client.GetKubeconfig(context.Background(), cliConf.Project, cliConf.Cluster, cliConf.Kubeconfig)
  53. if err != nil {
  54. return "", fmt.Errorf("error fetching kubeconfig for cluster: %w", err)
  55. }
  56. _, err = tmpFile.Write(resp.Kubeconfig)
  57. if err != nil {
  58. return "", fmt.Errorf("error writing kubeconfig to temp file: %w", err)
  59. }
  60. return tmpFile.Name(), nil
  61. }