kube-monkey icon indicating copy to clipboard operation
kube-monkey copied to clipboard

Kubectl exec into Kube-monkey pod

Open k8sVoodoo opened this issue 3 years ago • 0 comments

Could you append this func into your main.go and update the go.sum?? I believe this will fix the issue trying to kubectl exec into the pod to check the config.toml and anything else within the pod. ##################################################################################

import (
  "bytes"
  "fmt"

  v1 "k8s.io/api/core/v1"
  metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  "k8s.io/client-go/kubernetes"
  "k8s.io/client-go/kubernetes/scheme"
  "k8s.io/client-go/tools/clientcmd"
  "k8s.io/client-go/tools/remotecommand"
)

func ExecuteRemoteCommand(pod *v1.Pod, command string) (string, string, error) {
  kubeCfg := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
    clientcmd.NewDefaultClientConfigLoadingRules(),
    &clientcmd.ConfigOverrides{},
  )
  restCfg, err := kubeCfg.ClientConfig()
  if err != nil {
    return "", "", err
  }
  coreClient, err := kubernetes.NewForConfig(restCfg)
  if err != nil {
    return "", "", err
  }

  buf := &bytes.Buffer{}
  errBuf := &bytes.Buffer{}
  request := coreClient.CoreV1().RESTClient().
    Post().
    Namespace(pod.Namespace).
    Resource("pods").
    Name(pod.Name).
    SubResource("exec").
    VersionedParams(&v1.PodExecOptions{
      Command: []string{"/bin/sh", "-c", command},
      Stdin:   false,
      Stdout:  true,
      Stderr:  true,
      TTY:     true,
    }, scheme.ParameterCodec)
  exec, err := remotecommand.NewSPDYExecutor(restCfg, "POST", request.URL())
  err = exec.Stream(remotecommand.StreamOptions{
    Stdout: buf,
    Stderr: errBuf,
  })
  if err != nil {
    return "", "", fmt.Errorf("%w Failed executing command %s on %v/%v", err, command, pod.Namespace, pod.Name)
  }

  return buf.String(), errBuf.String(), nil
}

k8sVoodoo avatar Feb 15 '22 22:02 k8sVoodoo