How to filter finished jobs in kubernetes

4/14/2020

I'm trying to filter jobs that are complete using golang kubernetes client-go lib by their status.

I've checked other answers explaining how to get the jobs using kubectl, like this:

kubectl get job -o=jsonpath='{.items[?(@.status.succeeded==1)].metadata.name}'

But I don't know how to "turn" that jsonpath output into a filter or list options

If I were searching for pods by their status phase and a label I would do something like this:

listOptions := metav1.ListOptions{
    LabelSelector: "app.kubernetes.io/name=my-custom-job",
    FieldSelector: "status.phase=Running",
}
result, err := clientset.CoreV1().Pods("default").List(listOptions) 

But if I am going to implement the jsonpath {.items[?(@.status.succeeded==1)].metadata.name}

This is going to iterate through all jobs and check if the succeeded key under status is equal to one. For all jobs.

Is there a way to look for those jobs more "memory friendly" or a way to use jsonpaths like that in ListOptions?

-- AndreDurao
client-go
go
kubectl
kubernetes

1 Answer

4/14/2020

Yes, you can filter out, on the server-side, only finished jobs.

listOptions := metav1.ListOptions{
    FieldSelector: "status.successful=1",
}
result, err := clientset.BatchV1().Jobs("").List(listOptions) 

status.successful field from the job's spec is being directly mapped to status.succeeded field from metav1.ListOptions.FieldSelector. More info about that.

That being said, the list of available options to filter on the server-side is highly restricted. You can not filter using arbitrary fields from the spec (e.g. status.active or spec.parallelism). Github Issue on that.

-- Paul Brit
Source: StackOverflow