Imperative command for creating job and cronjob in Kubernetes

11/20/2019

Is this a valid imperative command for creating job?

kubectl create job my-job --image=busybox

I see this in https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands. But the command is not working. I am getting error as bellow:

Error: unknown flag: --image

What is the correct imperative command for creating job?

-- Rad4
cron
jobs
kubectl
kubernetes

2 Answers

12/31/2019

Using correct value for --restart field on "kubectl run" will result run command to create an deployment or job or cronjob

--restart='Always': The restart policy for this Pod.  Legal values [Always, OnFailure, Never].  If set to 'Always'
a deployment is created, if set to 'OnFailure' a job is created, if set to 'Never', a regular pod is created. For the
latter two --replicas must be 1.  Default 'Always', for CronJobs `Never`.

Use "kubectl run" for creating basic kubernetes job using imperatively command as below

master $ kubectl run nginx --image=nginx --restart=OnFailure --dry-run -o yaml > output.yaml

Above should result an "output.yaml" as below example, you can edit this yaml for advance configurations as needed and create job by "kubectl create -f output.yaml or if you just need basic job then remove --dry-run option from above command and you will get basic job created.

apiVersion: batch/v1
kind: Job
metadata:
  creationTimestamp: null
  labels:
    run: nginx
  name: nginx
spec:
  template:
    metadata:
      creationTimestamp: null
      labels:
        run: nginx
    spec:
      containers:
      - image: nginx
        name: nginx
        resources: {}
      restartPolicy: OnFailure
status: {}
-- DT.
Source: StackOverflow

11/20/2019

What you have should work, though it not recommended as an approach anymore. I would check what version of kubectl you have, and possibly upgrade it if you aren't using the latest.

That said, the more common approach these days is to write a YAML file containing the Job definition and then run kubectl apply -f myjob.yaml or similar. This file-driven approach allowed for more natural version control, editing, review, etc.

-- coderanger
Source: StackOverflow