Dhanu
Dhanu

Reputation: 49

While running specific command into a pod getting error

I'm trying to exec a command into a running pod. I'm using go K8sclient to achieve this but facing a issue. I also don't know if solution is correct or not. Can anyone please check and provide correct solution?

This is my code.

        namespace := getNamespace()
        podName := "maxscale-0"

        config, err := rest.InClusterConfig()
        if err != nil {
                log.Fatal(err)
        }

        clientset, err := kubernetes.NewForConfig(config)
        if err != nil {
                log.Fatal(err)
        }



        req := clientset.CoreV1().Pods(namespace).Exec(podName, &corev1.PodExecOptions{
                Command: []string{"sh", "-c", "grep -oP '\"name\": \"\\K[^\"]*' /var/lib/maxscale/MariaDB-Monitor_journal.json"},
        })

        // Set up a stream to capture the output
        execStream, err := req.Stream()
        if err != nil {
                fmt.Println(err)
                os.Exit(1)
        }

        // Print the output
        buf := new(bytes.Buffer)
        buf.ReadFrom(execStream)
        fmt.Println(buf.String())

The error I got is

clientset.CoreV1().Pods(namespace).Exec undefined (type "k8s.io/client-go/kubernetes/typed/core/v1".PodInterface has no field or method Exec)

Upvotes: 1

Views: 660

Answers (1)

Fariya Rahmat
Fariya Rahmat

Reputation: 3220

As @David Maze shared, to use k8's go client to exec command in a pod follow the below code:

import (
    "io"

    v1 "k8s.io/api/core/v1"
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/kubernetes/scheme"
    restclient "k8s.io/client-go/rest"
    "k8s.io/client-go/tools/remotecommand"
)

// ExecCmd exec command on specific pod and wait the command's output.
func ExecCmdExample(client kubernetes.Interface, config *restclient.Config, podName string,
    command string, stdin io.Reader, stdout io.Writer, stderr io.Writer) error {
    cmd := []string{
        "sh",
        "-c",
        command,
    }
    req := client.CoreV1().RESTClient().Post().Resource("pods").Name(podName).
        Namespace("default").SubResource("exec")
    option := &v1.PodExecOptions{
        Command: cmd,
        Stdin:   true,
        Stdout:  true,
        Stderr:  true,
        TTY:     true,
    }
    if stdin == nil {
        option.Stdin = false
    }
    req.VersionedParams(
        option,
        scheme.ParameterCodec,
    )
    exec, err := remotecommand.NewSPDYExecutor(config, "POST", req.URL())
    if err != nil {
        return err
    }
    err = exec.Stream(remotecommand.StreamOptions{
        Stdin:  stdin,
        Stdout: stdout,
        Stderr: stderr,
    })
    if err != nil {
        return err
    }

    return nil
}

Also refer to this link for more information

Upvotes: 1

Related Questions