Serge Bazanski | 7d1a0de | 2023-07-05 01:17:15 +0200 | [diff] [blame^] | 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "log" |
| 5 | "os" |
| 6 | "os/exec" |
| 7 | |
| 8 | "github.com/spf13/cobra" |
| 9 | |
| 10 | "source.monogon.dev/metropolis/cli/metroctl/core" |
| 11 | ) |
| 12 | |
| 13 | var k8sCommand = &cobra.Command{ |
| 14 | Short: "Manages kubernetes-specific functionality in Metropolis.", |
| 15 | Use: "k8s", |
| 16 | } |
| 17 | |
| 18 | var k8sConfigureCommand = &cobra.Command{ |
| 19 | Use: "configure", |
| 20 | Short: "Configures local `kubectl` for use with a Metropolis cluster.", |
| 21 | Long: `Configures a local kubectl instance (or any other Kubernetes application) |
| 22 | to connect to a Metropolis cluster. A cluster endpoint must be provided with the |
| 23 | --endpoints parameter.`, |
| 24 | Args: cobra.ExactArgs(0), |
| 25 | Run: doK8sConfigure, |
| 26 | } |
| 27 | |
| 28 | func doK8sConfigure(cmd *cobra.Command, _ []string) { |
| 29 | if len(flags.clusterEndpoints) < 1 { |
| 30 | log.Fatalf("k8s configure requires at least one cluster endpoint to be provided with the --endpoints parameter.") |
| 31 | } |
| 32 | |
| 33 | // If the user has metroctl in their path, use the metroctl from path as |
| 34 | // a credential plugin. Otherwise use the path to the currently-running |
| 35 | // metroctl. |
| 36 | metroctlPath := "metroctl" |
| 37 | if _, err := exec.LookPath("metroctl"); err != nil { |
| 38 | metroctlPath, err = os.Executable() |
| 39 | if err != nil { |
| 40 | log.Fatalf("Failed to create kubectl entry as metroctl is neither in PATH nor can its absolute path be determined: %v", err) |
| 41 | } |
| 42 | } |
| 43 | // TODO(q3k, issues/144): this only works as long as all nodes are kubernetes controller |
| 44 | // nodes. This won't be the case for too long. Figure this out. |
| 45 | configName := "metroctl" |
| 46 | if err := core.InstallKubeletConfig(metroctlPath, connectOptions(), configName, flags.clusterEndpoints[0]); err != nil { |
| 47 | log.Fatalf("Failed to install metroctl/k8s integration: %v", err) |
| 48 | } |
| 49 | log.Printf("Success! kubeconfig is set up. You can now run kubectl --context=%s ... to access the Kubernetes cluster.", configName) |
| 50 | } |
| 51 | |
| 52 | func init() { |
| 53 | k8sCommand.AddCommand(k8sConfigureCommand) |
| 54 | rootCmd.AddCommand(k8sCommand) |
| 55 | } |