I have a cobra CLI for my own stuff. Now I want to add commonly used executables e.g. kubectl, calicoctl as subcommands which will consume all arguments and flags like
mywrapper kubectl get all --all-namespaces
mywrapper kubectl create deployment nginx --image=nginx --port=80
Reproduce cobra project
mkdir mywrapper; cd mywrapper; go mod init mywrapper; cobra-cli init .
And add a subcommand e.g. kubectl
cobra-cli add kubectl
Then populate ./cmd/kubectl.go with
package cmd
import (
"fmt"
"os/exec"
"strings"
"github.com/spf13/cobra"
)
var kubectlCmd = &cobra.Command{
Use: "kubectl",
Short: "run kubectl",
Run: func(cmd *cobra.Command, args []string) {
out, err := exec.Command("/bin/bash", "-c", fmt.Sprintf("kubectl %v", strings.Join(args, " "))).Output()
if err != nil {
fmt.Println(err)
}
fmt.Println(string(out))
},
}
func init() {
rootCmd.AddCommand(kubectlCmd)
}
I can now run kubectl command e.g. go run . kubectl get pods. But it fails when flags are added e.g. go run . kubectl get pods --selector app=nginx