Add basic bashShell() function

Add the basic frame work for supporting spawning a bash shell by cli
command.

With this change, we can spawn a bash shell in the context of a cluster

$ k3d create -n my-cluster
$ k3d bash -n my-cluster
[my-cluster] $>

// execute commands with KUBECONFIG already set up
[my-cluster] $> kubectl get pods
pull/66/head
Andy Zhou 5 years ago
parent 9f276a68f3
commit 4ef6710e22
  1. 12
      cli/cluster.go
  2. 4
      cli/commands.go
  3. 31
      cli/shell.go
  4. 13
      main.go

@ -161,13 +161,15 @@ func getKubeConfig(cluster string) (string, error) {
return "", fmt.Errorf("Cluster %s does not exist", cluster)
}
// If kubeconfig.yaml has not been created, generate it now
if _, err := os.Stat(kubeConfigPath); os.IsNotExist(err) {
if err = createKubeConfigFile(cluster); err != nil {
// If kubeconfi.yaml has not been created, generate it now
if _, err := os.Stat(kubeConfigPath); err != nil {
if os.IsNotExist(err) {
if err = createKubeConfigFile(cluster); err != nil {
return "", err
}
} else {
return "", err
}
} else {
return "", err
}
return kubeConfigPath, nil

@ -353,3 +353,7 @@ func GetKubeConfig(c *cli.Context) error {
fmt.Println(kubeConfigPath)
return nil
}
func Bash(c *cli.Context) error {
return bashShell(c.String("name"))
}

@ -0,0 +1,31 @@
package run
import (
"fmt"
"os"
"os/exec"
)
func bashShell(cluster string) error {
kubeConfigPath, err := getKubeConfig(cluster)
if err != nil {
return err
}
cmd := exec.Command("/bin/bash", "--noprofile", "--norc")
// Set up stdio
cmd.Stdout = os.Stdout
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
// Set up Promot
setPS1 := fmt.Sprintf("PS1=[%s}%s", cluster, os.Getenv("PS1"))
// Set up KUBECONFIG
setKube := fmt.Sprintf("KUBECONFIG=%s", kubeConfigPath)
newEnv := append(os.Environ(), setPS1, setKube)
cmd.Env = newEnv
return cmd.Run()
}

@ -45,6 +45,19 @@ func main() {
Usage: "Check if docker is running",
Action: run.CheckTools,
},
{
// bash starts a bash shell in the context of a runnign cluster
Name: "bash",
Usage: "Start a bash subshell for a cluster",
Flags: []cli.Flag{
cli.StringFlag{
Name: "name, n",
Value: defaultK3sClusterName,
Usage: "Set a name for the cluster",
},
},
Action: run.Bash,
},
{
// create creates a new k3s cluster in docker containers
Name: "create",

Loading…
Cancel
Save