├── README.md └── kubectl-select.go /README.md: -------------------------------------------------------------------------------- 1 | ## kubectl-select 2 | This is a simple plugin to add the ability to interactively select kubernetes resources 3 | and print that resource to `stdout`. 4 | 5 | ### Examples 6 | 7 | ```sh 8 | # This allows interactive selection of a pod, and then creates a terminal session 9 | kubectl exec `kubectl select pods` -it sh 10 | ``` 11 | 12 | ### Building 13 | ``` 14 | go get github.com/brendandburns/kubectl-select 15 | ``` 16 | 17 | ### Installing 18 | ``` 19 | sudo cp $GOPATH/bin/kubectl-select /usr/local/bin/kubectl-select 20 | ``` 21 | -------------------------------------------------------------------------------- /kubectl-select.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "encoding/json" 6 | "fmt" 7 | "io/ioutil" 8 | "os" 9 | "os/exec" 10 | "strconv" 11 | "strings" 12 | ) 13 | 14 | func main() { 15 | args := append([]string{"get"}, os.Args[1:]...) 16 | args = append(args, "-o=json") 17 | cmd := exec.Command("kubectl", args...) 18 | stdout, _ := cmd.StdoutPipe() 19 | if err := cmd.Start(); err != nil { 20 | fmt.Printf("%v %v\n", cmd.Stderr, cmd.Stdout) 21 | panic(err) 22 | } 23 | data, _ := ioutil.ReadAll(stdout) 24 | cmd.Wait() 25 | 26 | var obj interface{} 27 | json.Unmarshal(data, &obj) 28 | items := obj.(map[string]interface{})["items"].([]interface{}) 29 | names := make([]string, len(items)) 30 | for ix := range items { 31 | item := items[ix] 32 | name := item.(map[string]interface{})["metadata"].(map[string]interface{})["name"] 33 | names[ix] = name.(string) 34 | os.Stderr.Write([]byte(fmt.Sprintf("%d] %s\n", (ix + 1), name))) 35 | } 36 | 37 | input := bufio.NewReader(os.Stdin) 38 | os.Stderr.Write([]byte("Select an item: ")) 39 | selection, _ := input.ReadString('\n') 40 | ix, _ := strconv.Atoi(strings.TrimSpace(selection)) 41 | ix = ix - 1 42 | if ix < 0 || ix >= len(items) { 43 | panic("invalid index") 44 | } 45 | fmt.Printf("%s\n", names[ix]) 46 | } 47 | --------------------------------------------------------------------------------