在kube-system命名空间下创建job: test-job,job执行ls -l命令:

测试环境:Mac+minikube

源码参考: ​​github源码地址​

package main

import (
"flag"
"golang.org/x/net/context"
batchv1 "k8s.io/api/batch/v1"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"log"
"os"
"path/filepath"
"strings"
)

//定义连接k8s集群的函数
func connectToK8s() *kubernetes.Clientset {
home,exists := os.LookupEnv("HOME")
if !exists {
home = "/root"
}

configPath := filepath.Join(home,".kube","config")
config,err := clientcmd.BuildConfigFromFlags("",configPath)
if err != nil{
log.Fatalln("failed to create K8s config")
}
clientset,err := kubernetes.NewForConfig(config)
if err != nil{
log.Fatalln("Failed to create K8s clientset")
}

return clientset
}

//定义k8s job模板
func launchK8sJob(clientset *kubernetes.Clientset,jobName *string,image *string,cmd *string){
jobs := clientset.BatchV1().Jobs("kube-system")
var backOffLimit int32 = 0

jobSpec := &batchv1.Job{
ObjectMeta: metav1.ObjectMeta{
Name: *jobName,
Namespace: "kube-system",
},
Spec: batchv1.JobSpec{
Template: v1.PodTemplateSpec{
Spec: v1.PodSpec{
Containers: []v1.Container{
{
Name: *jobName,
Image: *image,
Command: strings.Split(*cmd, " "),
},
},
//https://kubernetes.io/zh/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy
//Pod 的 spec 中包含一个 restartPolicy 字段,其可能取值包括 Always、OnFailure 和 Never。默认值是 Always。
//restartPolicy 适用于 Pod 中的所有容器。restartPolicy 仅针对同一节点上 kubelet 的容器重启动作。当 Pod 中的容器退出时,kubelet 会按指数回退 方式计算重启的延迟(10s、20s、40s、...),其最长延迟为 5 分钟。 一旦某容器执行了 10 分钟并且没有出现问题,kubelet 对该容器的重启回退计时器执行 重置操作。
RestartPolicy: v1.RestartPolicyNever,
},
},
//Specifies the number of retries before marking this job failed. Defaults to 6 +optional
//指定标记此任务失败之前的重试次数为0次,创建失败就不再创建。默认值为6
BackoffLimit: &backOffLimit,
},
}
_,err := jobs.Create(context.TODO(),jobSpec,metav1.CreateOptions{})
if err != nil{
log.Fatalln("Failed to create K8s job")
}

//print job details
log.Printf("Create K8s job successfully")
}

//定义主函数并使用flag包实现命令行的传参
func main(){
jobName := flag.String("jobname","test-job","请输入job的名字")
containerImage := flag.String("image","ubuntu:latest","请输入镜像名")
entryCommand := flag.String("command","ls -l","请输入命令")
flag.Parse()
clientset := connectToK8s()
launchK8sJob(clientset,jobName,containerImage,entryCommand)
}

使用默认参数执行:

✗ go run main.go
2022/04/08 17:42:05 Create K8s job successfully

➜ ~ kubectl get job -n kube-system
NAME COMPLETIONS DURATION AGE
test-job 0/1 12s 12s

➜ ~ kubectl get pod -n kube-system | grep test-job
test-job-h6z6c 0/1 Completed 0 8m53s

➜ ~ kubectl logs -f test-job-h6z6c -n kube-system
total 48
lrwxrwxrwx 1 root root 7 Apr 5 04:59 bin -> usr/bin
drwxr-xr-x 2 root root 4096 Apr 15 2020 boot
drwxr-xr-x 5 root root 360 Apr 8 09:45 dev
drwxr-xr-x 1 root root 4096 Apr 8 09:45 etc
drwxr-xr-x 2 root root 4096 Apr 15 2020 home
lrwxrwxrwx 1 root root 7 Apr 5 04:59 lib -> usr/lib
lrwxrwxrwx 1 root root 9 Apr 5 04:59 lib32 -> usr/lib32
lrwxrwxrwx 1 root root 9 Apr 5 04:59 lib64 -> usr/lib64
lrwxrwxrwx 1 root root 10 Apr 5 04:59 libx32 -> usr/libx32
drwxr-xr-x 2 root root 4096 Apr 5 04:59 media
drwxr-xr-x 2 root root 4096 Apr 5 04:59 mnt
drwxr-xr-x 2 root root 4096 Apr 5 04:59 opt
dr-xr-xr-x 265 root root 0 Apr 8 09:45 proc
drwx------ 2 root root 4096 Apr 5 05:02 root
drwxr-xr-x 1 root root 4096 Apr 8 09:45 run
lrwxrwxrwx 1 root root 8 Apr 5 04:59 sbin -> usr/sbin
drwxr-xr-x 2 root root 4096 Apr 5 04:59 srv
dr-xr-xr-x 12 root root 0 Apr 8 09:42 sys
drwxrwxrwt 2 root root 4096 Apr 5 05:02 tmp
drwxr-xr-x 13 root root 4096 Apr 5 04:59 usr
drwxr-xr-x 11 root root 4096 Apr 5 05:02 var

指定参数创建job

➜  client-go-create-job-command git:(master) ✗ go run main.go -command "ls -l home" -jobname "create-job-test"
2022/04/08 19:58:59 Create K8s job successfully

➜ ~ kubectl get job -n kube-system
NAME COMPLETIONS DURATION AGE
create-job-test 1/1 8s 2m50s

➜ ~ kubectl get pod -n kube-system
NAME READY STATUS RESTARTS AGE
coredns-64897985d-jq6tk 1/1 Running 1 (30d ago) 30d
create-job-test-lrm7z 0/1 Completed 0 12s

➜ ~ kubectl logs -f create-job-test-lrm7z -n kube-system
total 0