Search code examples
kuberneteskubectlkubernetes-cronjob

Kubectl command to check if cronjob is active or not


I'm trying to check if a particular cronjob is active or not through a shell script to perform some action if the job is not active. I tried using field-selector attribute for cronjob and the job created by the cron job as below

kubectl get cronjobs --field-selector status.active==1
kubectl get jobs --field-selector status.succeeded==1

But getting these field selectors are not supported. Is there any other field/way where I can check if the cronjob is active?


Solution

  • You could also set a label on your cronjob (and set the same label on the template part of the cronjob so it propagates to the underlying job that gets created), and then use that to select via:

    kubectl get cronjob -l label=value

    kubectl get job -l label=value

    Yes, it doesn't select by active/disabled state, but you did mention in your question you were checking a particular cronjob, so this would bring up the details of the specific cronjob or job for you to check

    To get the actual suspend state of the cronjob, you could pipe it to jq

    kubectl get cronjob cronjob-name | jq .items[0].spec.suspend

    This will give you "false" or "true" if the cronjob is suspended or not:

    $ kubectl get cronjob -n test
    NAME      SCHEDULE      SUSPEND   ACTIVE   LAST SCHEDULE   AGE
    api       */5 * * * *   False     0        78s             5m53s
    
    $ kubectl get cronjob -n test api -o json | jq .spec.suspend
    false
    

    You could probably also do this with jsonpath

    kubectl get cronjob -n test api -o jsonpath="{.spec.suspend}"
    

    From comment below, you use can active (i.e. currently running) , to see how many jobs are active (will be 0 if you don't have anything running)

    kubectl get cronjob -n test api -o jsonpath="{.spec.active}"