How can I filter in the kubernetes API (or kubectl) for Jobs owned by a given CronJob?

10/25/2019

I have several CronJobs, and I want to be able to query for a list of completed jobs for a specific one. I tried --field-selector metadata.ownerReferences.uid but that's not a supported field selector for batchv1.job (Looking at this it appears there are no useful field selectors for this use case).

I don't completely understand the DownwardAPI, but I was wondering if i can set a label on the job_spec (in the cronjob definition) that references the cronjobs uid, so I can then use label selectors to filter. I can't tell if thats possible.

Filtering for jobs by owner seems like a reasonable thing to be able to do, but I can't seem to find any useful information when searching around.

-- Joe Ceresini
kubernetes
kubernetes-cronjob

1 Answer

10/25/2019

You can use this two commands to get a list of jobs belonging to a Cronjob:

uid=$(kubectl get cronjob [MY-CRONJOB-NAME] --output jsonpath='{.metadata.uid}')
kubectl get jobs -o json | jq -r --arg uid "$uid" '.items | map(select(.metadata.ownerReferences[]? | .uid==$uid) | .metadata.name) | .[]'

The first command fetches the metadata.uid from your specified [MY-CRONJOB-NAME]. Then, a kubectl get all jobs, and the output is processed with jq to filter them by the .metadata.ownerReferences.uid.


If you want a more simple approach, you can play with the --custom-columns flag. The following example list all jobs and their respective controller names:

kubectl get jobs --all-namespaces -o custom-columns=NAME:.metadata.name,CONTROLLER:.metadata.ownerReferences[].name,NAMESPACE:.metadata.namespace
-- Eduardo Baitello
Source: StackOverflow