Repeated calls to kubernetes job

For a job in the normal state, if you use apply or create, there will be the problem of unchanged or existing name

But in many cases, I have a yaml that needs to be executed manually occasionally (no cron is required)

  • First, use generatename + kubectl create to generate a new name each time
  • Add TTL, so that the old jobs created will be cleaned up in time
apiVersion: batch/v1
kind: Job
metadata:
  generateName: pi-with-ttl-
spec:
  ttlSecondsAfterFinished: 10
  template:
    spec:
      containers:
      - name: pi
        image: perl
        command: ["perl",  "-Mbignum=bpi", "-wle", "print bpi(2000)"]
      restartPolicy: Never

It should be noted that job TTL is a new feature of 1.21. In the old version of kubernetes, you may need to use cronjob to clean up these executed jobs regularly

kubectl delete jobs `kubectl get jobs -o custom-columns=:.metadata.name -n lizhe` -n lizhe

However, the above solution also suffers from the fact that cronjobs may delete running jobs by mistake

Be careful

Send a Message