79187299

Date: 2024-11-14 03:18:42
Score: 1
Natty:
Report link

I have a go file which can run command in a nginx Pod, is that what you want?

go.mod

module my.com/test
                                                    
go 1.20 

require (                                                            
        k8s.io/api v0.28.4                            
        k8s.io/client-go v0.28.4                                           
        k8s.io/kubectl v0.28.4                              
) 

main.go

package main

import (
    "bytes"
    "fmt"

    v1 "k8s.io/api/core/v1"
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/tools/clientcmd"
    "k8s.io/client-go/tools/remotecommand"
    "k8s.io/kubectl/pkg/scheme"
)

func executeCommandInPod(kubeconfigPath, pod, namespace, command string) (string, string, error) {
    // Build kubeconfig from the provided path
    config, err := clientcmd.BuildConfigFromFlags("", kubeconfigPath)
    if err != nil {
        return "", "", fmt.Errorf("failed to build kubeconfig: %v", err)
    }

    // Create a new clientset based on the provided kubeconfig
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        return "", "", fmt.Errorf("failed to create clientset: %v", err)
    }

    // Get the pod's name and namespace
    podName := pod
    podNamespace := namespace

    // Build the command to be executed in the pod
    cmd := []string{"sh", "-c", command}

    // Execute the command in the pod
    req := clientset.CoreV1().RESTClient().Post().
        Resource("pods").
        Name(podName).
        Namespace(podNamespace).
        SubResource("exec").
        VersionedParams(&v1.PodExecOptions{
            Command: cmd,
            Stdin:   false,
            Stdout:  true,
            Stderr:  true,
            TTY:     false,
        }, scheme.ParameterCodec)

    executor, err := remotecommand.NewSPDYExecutor(config, "POST", req.URL())
    if err != nil {
        return "", "", fmt.Errorf("failed to create executor: %v", err)
    }

    var stdout, stderr bytes.Buffer
    err = executor.Stream(remotecommand.StreamOptions{
        Stdout: &stdout,
        Stderr: &stderr,
        Tty:    false,
    })
    if err != nil {
        return "", "", fmt.Errorf("failed to execute command in pod: %v", err)
    }

    return stdout.String(), stderr.String(), nil
}

func main() {
    stdout, stderr, err := executeCommandInPod("/tmp/config", "nginx-0", "default", "ls /")
    fmt.Println(stdout, stderr, err)
}
Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • Low reputation (0.5):
Posted by: linlin