Last active
October 16, 2019 10:28
-
-
Save metrue/16200de04531137ab4f5bc34e8816551 to your computer and use it in GitHub Desktop.
exec command in K8S Pod
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func ExecPod(namespace string, name string, command ...string) error { | |
config, err := clientcmd.BuildConfigFromKubeconfigGetter("", clientcmd.NewDefaultClientConfigLoadingRules().Load) | |
if err != nil { | |
return nil, err | |
} | |
k, err := kubernetes.NewForConfig(config) | |
if err != nil { | |
return nil, err | |
} | |
config, err := clientcmd.BuildConfigFromFlags("<master url>", "<path to kube config>") | |
if err != nil { | |
return err | |
} | |
fmt.Printf("executing command %q", strings.Join(command, " ")) | |
var ( | |
execOut bytes.Buffer | |
execErr bytes.Buffer | |
) | |
pod, err := k.CoreV1().Pods(namespace).Get(name, metav1.GetOptions{}) | |
if err != nil { | |
return fmt.Errorf("could not get pod info: %v", err) | |
} | |
// iterate through all containers looking for the one running PostgreSQL. | |
if len(pod.Spec.Containers) <= 0 { | |
return fmt.Errorf("no container found on Pod %s", pod.Name) | |
} | |
req := k.CoreV1().RESTClient().Post(). | |
Resource("pods"). | |
Name(name). | |
Namespace(namespace). | |
SubResource("exec") | |
req.VersionedParams(&v1.PodExecOptions{ | |
Container: pod.Spec.Containers[0].Name, | |
Command: command, | |
Stdout: true, | |
Stderr: true, | |
}, scheme.ParameterCodec) | |
// restConfig, err := rest.InClusterConfig() | |
// if err != nil { | |
// return fmt.Errorf("failed to get in cluster config: %v", err) | |
// } | |
exec, err := remotecommand.NewSPDYExecutor(config, "POST", req.URL()) | |
if err != nil { | |
return fmt.Errorf("failed to init executor: %v", err) | |
} | |
err = exec.Stream(remotecommand.StreamOptions{ | |
Stdout: &execOut, | |
Stderr: &execErr, | |
Tty: false, | |
}) | |
if err != nil { | |
return fmt.Errorf("could not execute: %v", err) | |
} | |
if execErr.Len() > 0 { | |
return fmt.Errorf("stderr: %v", execErr.String()) | |
} | |
fmt.Println("---------------") | |
fmt.Println(execOut.String()) | |
fmt.Println("---------------") | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment