diff --git a/tool/tsh/common/kube_proxy.go b/tool/tsh/common/kube_proxy.go index 89a05c11c154d..d2b23b1f73612 100644 --- a/tool/tsh/common/kube_proxy.go +++ b/tool/tsh/common/kube_proxy.go @@ -23,6 +23,7 @@ import ( "crypto/tls" "encoding/pem" "fmt" + "io" "net" "os" "os/exec" @@ -62,6 +63,7 @@ type proxyKubeCommand struct { labels string predicateExpression string + exec bool } func newProxyKubeCommand(parent *kingpin.CmdClause) *proxyKubeCommand { @@ -84,6 +86,7 @@ func newProxyKubeCommand(parent *kingpin.CmdClause) *proxyKubeCommand { // This works as an hint to the user that the context name can be customized. Default(kubeconfig.ContextName("{{.ClusterName}}", "{{.KubeName}}")). StringVar(&c.overrideContextName) + c.Flag("exec", "Run the proxy in the background and reexec into a new shell with $KUBECONFIG already pointed to our config file.").BoolVar(&c.exec) return c } @@ -103,6 +106,7 @@ func (c *proxyKubeCommand) run(cf *CLIConf) error { if err != nil { return trace.Wrap(err) } + if cf.Headless { tc.AllowHeadless = true } @@ -118,7 +122,10 @@ func (c *proxyKubeCommand) run(cf *CLIConf) error { } defer localProxy.Close() - if err := c.printTemplate(cf, localProxy); err != nil { + // re-exec into a new shell with $KUBECONFIG already pointed to our config file + // if --exec flag is set or headless mode is enabled. + reexecIntoShell := cf.Headless || c.exec + if err := c.printTemplate(cf.Stdout(), reexecIntoShell, localProxy); err != nil { return trace.Wrap(err) } @@ -135,7 +142,7 @@ func (c *proxyKubeCommand) run(cf *CLIConf) error { return trace.Wrap(cf.RunCommand(cmd)) } - if cf.Headless { + if reexecIntoShell { // If headless, run proxy in the background and reexec into a new shell with $KUBECONFIG already pointed to // our config file return trace.Wrap(runHeadlessKubeProxy(cf, localProxy)) @@ -261,13 +268,13 @@ func (c *proxyKubeCommand) printPrepare(cf *CLIConf, title string, clusters kube fmt.Fprintln(cf.Stdout(), table.AsBuffer().String()) } -func (c *proxyKubeCommand) printTemplate(cf *CLIConf, localProxy *kubeLocalProxy) error { - if cf.Headless { - return trace.Wrap(proxyKubeHeadlessTemplate.Execute(cf.Stdout(), map[string]interface{}{ +func (c *proxyKubeCommand) printTemplate(w io.Writer, isReexec bool, localProxy *kubeLocalProxy) error { + if isReexec { + return trace.Wrap(proxyKubeHeadlessTemplate.Execute(w, map[string]interface{}{ "multipleContexts": len(localProxy.kubeconfig.Contexts) > 1, })) } - return trace.Wrap(proxyKubeTemplate.Execute(cf.Stdout(), map[string]interface{}{ + return trace.Wrap(proxyKubeTemplate.Execute(w, map[string]interface{}{ "addr": localProxy.GetAddr(), "format": c.format, "randomPort": c.port == "",