通过kubernetes的API在容器内执行命令代码段

时间:May 13, 2021 分类:

目录:

以下代码,用于Pod重启

        pod, err := client.CoreV1().Pods(namespace).Get(ctx, podname, metav1.GetOptions{})
    if err != nil {
        return err
    }
    //restart := pod.Status.ContainerStatuses[0].RestartCount
    containerName := pod.Spec.Containers[0].Name
    command := []string{"kill", "1"}
    req := client.CoreV1().RESTClient().Post().Resource("pods").Name(podname).Namespace(namespace).SubResource("exec").VersionedParams(
        &apiv1.PodExecOptions{
            Container: containerName,
            Command:   command,
            Stdout:    true,
            Stderr:    true,
            Stdin:     true,
            TTY:       true,
        }, scheme.ParameterCodec)
    exec, err := remotecommand.NewSPDYExecutor(restclient, "POST", req.URL())
    if err != nil {
        return err
    }
    err = exec.Stream(
        remotecommand.StreamOptions{
            Stdin:  &stdin,
            Stderr: &stderr,
            Stdout: &stdout,
            Tty:    true,
        },
    )