Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kubernetes-client javascript - create job from cronjob

Tags:

What will be the equivalent for creating a job:

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

using javascript kubernetes-client ?

like image 510
AsafG Avatar asked Mar 04 '21 09:03

AsafG


2 Answers

No, unfortunately you can't.

Please check my old answer in Create job from cronjob in kubernetes .yaml file question.

In short: you are able to do that (create job from cronjob) only using kubectl cli


Way to create regular job, without --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))

Example was taken from @Popopame answer in How to create a Job and a secret from Kubernetes Javascript Client

like image 172
Vit Avatar answered Sep 28 '22 06:09

Vit


Found the solution to my question, with the help of this comment

This is how it looks like with javascript kubernetes-client, used in a pod inside the cluster (rbac permission might be needed, im running on k8s docker-desktop so didnt need):

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;
    }
}
like image 28
AsafG Avatar answered Sep 28 '22 06:09

AsafG