Skip to content

Commit

Permalink
Add possibility to exec a command in a pod. (#158)
Browse files Browse the repository at this point in the history
* Add possibility to exec a command in a pod.

* Add possibility to exec a command in a pod.
  • Loading branch information
Christian Bianchi committed Mar 11, 2024
1 parent ad32e68 commit d64f5ba
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- Add possibility to exec a command in a pod.

## [0.15.0] - 2024-02-26

### Fixed
Expand Down
58 changes: 58 additions & 0 deletions pkg/client/exec.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package client

import (
"bytes"
"context"
"fmt"

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

"github.com/giantswarm/clustertest/pkg/logger"
)

func (c *Client) ExecInPod(ctx context.Context, podName, namespace, containerName string, command []string) (string, string, error) {
logger.Log("Running %v in container %q in pod %q", command, containerName, podName)

tty := true

coreClient, err := kubernetes.NewForConfig(c.config)
if err != nil {
return "", "", fmt.Errorf("failed initializing kubernetes core client - %v", err)
}

req := coreClient.CoreV1().RESTClient().Post().
Resource("pods").
Name(podName).
Namespace(namespace).
SubResource("exec").
Param("container", containerName)
req.VersionedParams(&corev1.PodExecOptions{
Container: containerName,
Command: command,
Stdin: false,
Stdout: true,
Stderr: true,
TTY: tty,
}, scheme.ParameterCodec)

var stdout, stderr bytes.Buffer
exec, err := remotecommand.NewSPDYExecutor(c.config, "POST", req.URL())
if err != nil {
return "", "", fmt.Errorf("failed to exec command in pod - %v", err)
}

err = exec.StreamWithContext(ctx, remotecommand.StreamOptions{
Stdin: nil,
Stdout: &stdout,
Stderr: &stderr,
Tty: tty,
})
if err != nil {
return "", "", fmt.Errorf("failed to exec command in pod - %v", err)
}

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

0 comments on commit d64f5ba

Please sign in to comment.