Exec Command in a Kubernetes Pod Using Go Client
Issue:
The provided code snippet attempts to execute a command inside a pod using the Kubernetes Go client but encounters an error when attempting to stream the command output.
Solution:
The issue lies in the usage of remotecommand.NewExecutor(), which is intended for HTTP/1.1 connections. For SPDY connections, which are typically used in Kubernetes clusters, you should instead use remotecommand.NewSPDYExecutor().
Modified Code:
import ( "fmt" "io" "os" container "k8s.io/api/core/v1" meta "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" restclient "k8s.io/client-go/rest" cmd "k8s.io/client-go/tools/remotecommand" ) func main() { // Replace with your own config or use in-cluster config config := &restclient.Config{ Host: "https://192.168.8.175:8080", // Insecure if using a self-signed certificate Insecure: true, } // Create a Kubernetes client client, err := kubernetes.NewForConfig(config) if err != nil { fmt.Println(err) return } // Define the pod and container to execute the command in podName := "wordpress-mysql-213049546-29s7d" namespace := "default" containerName := "mysql" // Define the command to execute command := []string{"ls"} // Create the PodExecOptions object execOptions := container.PodExecOptions{ Container: containerName, Command: []string{"ls"}, Stdin: true, Stdout: true, Stderr: true, } // Create the request req := client.CoreV1().RESTClient().Post().Resource("pods").Namespace(namespace).Name(podName).SubResource("exec") // Pass the PodExecOptions object as VersionedParams request := req.VersionedParams(&execOptions, meta.ParameterCodec) // Execute the command exec, err := cmd.NewSPDYExecutor(config, "POST", request.URL()) if err != nil { fmt.Println(err) return } // Stream the output of the command to stdout and stderr err = exec.Stream(cmd.StreamOptions{ Stdin: os.Stdin, Stdout: os.Stdout, Stderr: os.Stderr, }) if err != nil { fmt.Println(err) return } }
The above is the detailed content of How to Correctly Execute a Command in a Kubernetes Pod Using the Go Client and Handle SPDY Connections?. For more information, please follow other related articles on the PHP Chinese website!