Kubernetes Exec Command Example Using Go Client
Problem:
Executing commands in a pod using the Kubernetes Go client can be challenging. Users may encounter errors without clear messages when attempting to stream the execution output.
Solution:
To correctly execute commands in a pod with the Kubernetes Go client, follow these steps:
Note:
The code example provided in the question uses an incorrect version of the PodExecOptions struct. The correct version is from the v1 package (not the unversioned package).
Working Example:
The following code demonstrates a working example of executing commands in a pod using the Kubernetes Go client:
package k8s 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 }
This code correctly uses the v1 version of PodExecOptions and sets the TTY parameter to true, enabling interactive command execution if desired.
The above is the detailed content of How to Execute Kubernetes Exec Commands Using the Go Client?. For more information, please follow other related articles on the PHP Chinese website!