How to trigger a Kubernetes cronjob

2 min read | by Jordi Prats

If you deploy a Cronjob on Kubernetes it can be useful to test it out by manually triggering a run rather than to wait until it is run according by it's schedule.

Let's assume we have the following Cronjob that we want to run:

$ kubectl get cronjob
NAME                    SCHEDULE    SUSPEND   ACTIVE   LAST SCHEDULE   AGE
pet2cattle-sitemapgen   0 5 * * *   False     0        <none>          13m

To be able to trigger it's execution we will have simulate it by creating a job using the cronjob as a template:

$ kubectl create job --from=cronjob/pet2cattle-sitemapgen p2c-sitmapgen-manual-001
job.batch/p2c-sitmapgen-manual-001 created

We will be able to see whether the Job have completed using kubectl get jobs:

$ kubectl get jobs
NAME                       COMPLETIONS   DURATION   AGE
helm-install-traefik       1/1           37s        72d
p2c-sitmapgen-manual-001   1/1           6s         6s

To check the pod that actually run the Job, we will have to describe the job:

$ kubectl describe job p2c-sitmapgen-manual-001
Name:           p2c-sitmapgen-manual-001
Namespace:      kube-system
Selector:       controller-uid=f95b858c-d58b-4d7c-ab9f-a695bc4bff0d
Labels:         controller-uid=f95b858c-d58b-4d7c-ab9f-a695bc4bff0d
                job-name=p2c-sitmapgen-manual-001
Annotations:    cronjob.kubernetes.io/instantiate: manual
Parallelism:    1
Completions:    1
Start Time:     Sat, 02 Jan 2021 22:09:46 +0100
Completed At:   Sat, 02 Jan 2021 22:09:52 +0100
Duration:       6s
Pods Statuses:  0 Running / 1 Succeeded / 0 Failed
Pod Template:
  Labels:  controller-uid=f95b858c-d58b-4d7c-ab9f-a695bc4bff0d
           job-name=p2c-sitmapgen-manual-001
  Containers:
   pet2cattle-sitemapgen:
    Image:      172.18.1.46:5000/p2c:3.1
    Port:       <none>
    Host Port:  <none>
    Command:
      /usr/local/bin/python
      /code/sitemapgen.py
    Environment:
      MINIO_URL:         http://pet2cattle-minio.kube-system.svc.cluster.local:9000
      MINIO_BUCKET:      pet2cattle
      MINIO_ACCESS_KEY:  <set to the key 'accesskey' in secret 'pet2cattle-minio'>  Optional: false
      MINIO_SECRET_KEY:  <set to the key 'secretkey' in secret 'pet2cattle-minio'>  Optional: false
    Mounts:              <none>
  Volumes:               <none>
Events:
  Type    Reason            Age    From            Message
  ----    ------            ----   ----            -------
  Normal  SuccessfulCreate  5m29s  job-controller  Created pod: p2c-sitmapgen-manual-001-5ncj9
  Normal  Completed         5m23s  job-controller  Job completed

On the events section we can find which pod have been created to run this job, so we can, for example, check it's logs:

$ kubectl get pod p2c-sitmapgen-manual-001-5ncj9
NAME                             READY   STATUS      RESTARTS   AGE
p2c-sitmapgen-manual-001-5ncj9   0/1     Completed   0          5m42s

Posted on 21/01/2021