Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can use the following client-go method to remove k8s Jobs and their associated pods:

  1. First, create a clientset instance:
import (
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/rest"
)

config, err := rest.InClusterConfig()
if err != nil {
    panic(err.Error())
}

clientset, err := kubernetes.NewForConfig(config)
if err != nil {
    panic(err.Error())
}
  1. Then, create a Job object using the clientset:
jobClient := clientset.BatchV1().Jobs(namespace)

err = jobClient.Delete(jobName, &metav1.DeleteOptions{})
if err != nil {
    panic(err.Error())
}

  1. Finally, delete the associated pods using the clientset:
podClient := clientset.CoreV1().Pods(namespace)

selector := fmt.Sprintf("job-name=%s", jobName)

err = podClient.DeleteCollection(&metav1.DeleteOptions{}, metav1.ListOptions{
    LabelSelector: selector,
})

if err != nil {
    panic(err.Error())
}

With the above client-go methods, you can easily remove k8s Jobs and their associated pods.