Skip to content

Instantly share code, notes, and snippets.

@p0lyn0mial
Last active April 13, 2018 13:12
Show Gist options
  • Save p0lyn0mial/051e9068800f83630aceb1a01c00c100 to your computer and use it in GitHub Desktop.
Save p0lyn0mial/051e9068800f83630aceb1a01c00c100 to your computer and use it in GitHub Desktop.
Shows how to exec into the pod using k8s client-go library
package main
import (
"flag"
"os"
"strings"
"github.com/golang/glog"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/tools/remotecommand"
)
func main() {
var kubeconfig string
var podName string
var podNamespace string
var containerName string
var commandStr string
var command []string
flag.StringVar(&kubeconfig, "kubeconfig", "", "path to the kubeconfig.")
flag.StringVar(&podName, "podName", "", "the name of the pod we are going to exec into")
flag.StringVar(&podNamespace, "podNamespace", "", "the namespace of the pod")
flag.StringVar(&containerName, "containerName", "", "the name the container we are going to exec into")
flag.StringVar(&commandStr, "command", "", "the command to execute")
flag.Parse()
if len(kubeconfig) == 0 {
glog.Fatal("kubeconfig not provided!")
}
if len(podNamespace) == 0 || len(podName) == 0 || len(containerName) == 0 || len(commandStr) == 0 {
glog.Fatal("invalid configuration provided")
}
command = strings.Split(commandStr, " ")
cfg, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
glog.Fatalf("error building kubeconfig: %v", err)
}
// satisfy RESTClientFor
gv := v1.SchemeGroupVersion
cfg.GroupVersion = &gv
cfg.APIPath = "/api"
cfg.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}
if cfg.UserAgent == "" {
cfg.UserAgent = restclient.DefaultKubernetesUserAgent()
}
restClient, err := restclient.RESTClientFor(cfg)
if err != nil {
glog.Fatal(err)
}
req := restClient.Post().
Resource("pods").
Name(podName).
Namespace(podNamespace).
SubResource("exec").
Param("container", containerName)
req.VersionedParams(&v1.PodExecOptions{
Container: containerName,
Command: command,
Stdin: false,
Stdout: true,
Stderr: true,
TTY: false,
}, scheme.ParameterCodec)
exec, err := remotecommand.NewSPDYExecutor(cfg, "POST", req.URL())
if err != nil {
glog.Fatal(err)
}
var terminalSizeQueue remotecommand.TerminalSizeQueue
err = exec.Stream(remotecommand.StreamOptions{
Stdin: nil,
Stdout: os.Stdout,
Stderr: os.Stderr,
Tty: false,
TerminalSizeQueue: terminalSizeQueue,
})
if err != nil {
glog.Fatal(err)
}
}
@p0lyn0mial
Copy link
Author

run with the following flags:
-kubeconfig /home/lukasz/.kube/config -podName shell-demo -podNamespace rfmm2mwq5s -containerName nginx -command "mkdir /tmp/test"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment