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 ?
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
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With