kubernetes-client javascript - 从 cronjob 创建作业

kubernetes-client javascript - create job from cronjob

创建工作的等价物是什么:

kubectl -n my-ns create job --from=cronjob/my-cron-job my-job

使用 javascript kubernetes-client ?

不,遗憾的是你不能。

请检查我的 in 问题。

简而言之:你可以做到(从 cronjob 创建作业)仅使用 kubectl cli


创建常规工作的方法,没有 --from=cronjob:

const k8s = require('@kubernetes/client-node');
const kc = new k8s.KubeConfig();

kc.loadFromCluster();

const k8sBatchV1Api = kc.makeApiClient(k8s.BatchV1Api);

//creation of the job
k8sBatchV1Api.createNamespacedJob('dev', {
    apiVersion: 'batch/v1',
    kind: 'Job',
    metadata: {
    ...
       }
    },
    spec: {
    ...
          }
       }
    }}).catch(e => console.log(e))

示例取自@Popopame 在

中的回答

在这个 comment

的帮助下找到了我的问题的解决方案

这是 javascript kubernetes-client 的样子,在集群内的 pod 中使用(可能需要 rbac 权限,im 运行 on k8s docker-desktop 所以不需要):

const createJobFromCronJob = async (
    cronJobNamespace: string,
    cronJobName: string,
    jobNamespace: string,
    jobName: string) => {
    // next 4 lines can be initialized somewhere else
    const kubeConfig = new k8s.KubeConfig();
    kubeConfig.loadFromCluster();
    const batchV1Api = kubeConfig.makeApiClient(k8s.BatchV1Api);
    const batchV1beta1Api = kubeConfig.makeApiClient(k8s.BatchV1beta1Api);
    try {
        const cronJob = await batchV1beta1Api.readNamespacedCronJob(cronJobName, cronJobNamespace);
        const cronJobSpec = cronJob.body.spec.jobTemplate.spec;
        const job = new k8s.V1Job();
        const metadata = new k8s.V1ObjectMeta();
        job.apiVersion = 'batch/v1';
        job.kind = 'Job';
        job.spec = cronJobSpec;
        metadata.name = jobName;
        metadata.annotations = {
            'cronjob.kubernetes.io/instantiate': 'manual',
        };
        job.metadata = metadata;
        const result = await batchV1Api.createNamespacedJob(jobNamespace, job);
        console.log('job created');
    } catch (err) {
        console.error(`failed to create job: ${err.message}`);
        throw err;
    }
}