在 Kubernetes 禁用 cronjob

我已经安排了一个在 Kubernetes 作为 CronJob运行的应用程序。当代码发生变化时,我也会改变 CronJob的图像。

我正在寻找一个选项,其中我可以禁用当前运行的 CronJob和部署一个新的 CronJob与最新的图像版本。

如何在 Kubernetes 禁用一个 CronJob而不删除它的 Deployment

88122 次浏览

You can use something which will be valid with respect to Cron Job format but actually that date should not appear anytime in calendar date like 31 Feb.

* * 31 2 *

Edit your current cronjob resource to include the .spec.suspend field and set it to true. Any currently running jobs will complete but future jobs will be suspended.

If you also need to stop currently running jobs, you'll have to delete them

If you want to suspend cronjob via patch, use:

kubectl patch cronjobs <job-name> -p '{"spec" : {"suspend" : true }}'
kubectl patch cronjobs job-name -p "{\"spec\" : {\"suspend\" : true }}"

Option 1 with command line

$ kubectl patch cronjobs $(kubectl get cronjobs | awk '{ print $1 }' | tail -n +2) -p '{"spec" : {"suspend" : true }}'

Option 2 with command line:

$ kubectl get cronjobs | grep False | cut -d' ' -f 1 | xargs kubectl patch cronjobs -p '{"spec" : {"suspend" : true }}'

Option 3 creating resource quotas. I believe that is the cleaner option.

cat <<EOF | kubectl apply -f -
# https://kubernetes.io/docs/concepts/policy/resource-quotas/#object-count-quota
apiVersion: v1
kind: ResourceQuota
metadata:
name: limit-generic-resources
spec:
hard:
pods: "0"
count/persistentvolumeclaims : "0"
count/services : "0"
count/secrets : "0"
count/configmaps : "0"
count/replicationcontrollers : "0"
count/deployments.apps : "0"
count/replicasets.apps : "0"
count/statefulsets.apps : "0"
count/jobs.batch : "0"
count/cronjobs.batch : "0"
EOF

Here's arguably the simplest way you can patch multiple CronJobs (and other patch-able objects like Deployments or Pods):

kubectl patch $(kubectl get cronjob -o name | grep my-filter) -p '{"spec" : {"suspend" : true }}'


Notice the use of -o name which simplifies getting a list of objects (here: CronJobs) names to process (without the need to parse a table with awk).

You can patch all of them at once or just a subset of names restricted to those meeting filtering criteria (here: containing my-filter).