kubectl.go 1.8 KB

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