Skip to content

Commit 3084df3

Browse files
Use batchv1.Job to auto cleanup finished pod
1 parent 376850b commit 3084df3

File tree

1 file changed

+33
-19
lines changed

1 file changed

+33
-19
lines changed

pkg/cmd/ssh-proxy.go

Lines changed: 33 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,19 @@ import (
1010
"time"
1111

1212
"github.com/spf13/cobra"
13+
batchv1 "k8s.io/api/batch/v1"
1314
core "k8s.io/api/core/v1"
15+
v1 "k8s.io/api/core/v1"
1416
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
1517
"k8s.io/client-go/kubernetes"
1618
"k8s.io/client-go/rest"
1719

1820
"k8s.io/cli-runtime/pkg/genericclioptions"
1921
)
2022

23+
// Cleanup ssh-proxy job and pod immediately after completion
24+
const jobTTL int32 = 0
25+
2126
var (
2227
use = "%[1]s [flags] ssh|scp|sftp [flags] [arguments]"
2328

@@ -147,12 +152,12 @@ func (o *ProxyOptions) Run(args []string) error {
147152
sshProxyPod = pods.Items[0].Name
148153
} else {
149154
fmt.Printf("No proxy pod found in %s namespace\n", o.namespace)
150-
pod := getPodObject()
151-
pod, err := clientset.CoreV1().Pods(o.namespace).Create(context.TODO(), pod, metav1.CreateOptions{})
155+
job := getJobObject()
156+
job, err := clientset.BatchV1().Jobs(o.namespace).Create(context.TODO(), job, metav1.CreateOptions{})
152157
if err != nil {
153158
return err
154159
}
155-
sshProxyPod = pod.Name
160+
sshProxyPod = job.Spec.Template.ObjectMeta.Name
156161
fmt.Printf("pod/%s created\n", sshProxyPod)
157162
}
158163

@@ -201,24 +206,33 @@ func baseName() string {
201206
return fileName
202207
}
203208

204-
func getPodObject() *core.Pod {
205-
return &core.Pod{
209+
func getJobObject() *batchv1.Job {
210+
ttl := jobTTL
211+
return &batchv1.Job{
206212
ObjectMeta: metav1.ObjectMeta{
207-
GenerateName: "ssh-proxy-",
208-
Labels: map[string]string{
209-
"app": "kubectl-ssh-proxy",
210-
},
213+
Name: "ssh-proxy",
211214
},
212-
Spec: core.PodSpec{
213-
RestartPolicy: core.RestartPolicyNever,
214-
Containers: []core.Container{
215-
{
216-
Name: "busybox",
217-
Image: "busybox:latest",
218-
ImagePullPolicy: core.PullIfNotPresent,
219-
Command: []string{
220-
"sleep",
221-
"12h",
215+
Spec: batchv1.JobSpec{
216+
TTLSecondsAfterFinished: &ttl,
217+
Template: v1.PodTemplateSpec{
218+
ObjectMeta: metav1.ObjectMeta{
219+
Name: "ssh-proxy",
220+
Labels: map[string]string{
221+
"app": "kubectl-ssh-proxy",
222+
},
223+
},
224+
Spec: v1.PodSpec{
225+
RestartPolicy: v1.RestartPolicyNever,
226+
Containers: []core.Container{
227+
{
228+
Name: "busybox",
229+
Image: "public.ecr.aws/docker/library/busybox:glibc",
230+
ImagePullPolicy: core.PullIfNotPresent,
231+
Command: []string{
232+
"sleep",
233+
"12h",
234+
},
235+
},
222236
},
223237
},
224238
},

0 commit comments

Comments
 (0)