SmCaterpillar
SmCaterpillar

Reputation: 7020

How to change the schedule of a Kubernetes cronjob or how to start it manually?

Is there a simple way to change the schedule of a kubernetes cronjob like kubectl change cronjob my-cronjob "10 10 * * *"? Or any other way without needing to do kubectl apply -f deployment.yml? The latter can be extremely cumbersome in a complex CI/CD setting because manually editing the deployment yaml is often not desired, especially not if the file is created from a template in the build process.

Alternatively, is there a way to start a cronjob manually? For instance, a job is scheduled to start in 22 hours, but I want to trigger it manually once now without changing the cron schedule for good (for testing or an initial run)?

Upvotes: 26

Views: 39470

Answers (5)

rk17
rk17

Reputation: 61

From @SmCaterpillar answer above kubectl patch my-cronjob -p '{"spec":{"schedule": "42 11 * * *"}}', I was getting the error: unable to parse "'{spec:{schedule:": yaml: found unexpected end of stream

If someone else is facing a similar issue, replace the last part of the command with -

"{\"spec\":{\"schedule\": \"42 11 * * *\"}}"

Upvotes: 3

Jakub Czaplicki
Jakub Czaplicki

Reputation: 1847

And if you want to do patch a k8s cronjob schedule with the Python kubernetes library, you can do this like that:

from kubernetes import client, config

config.load_kube_config()
v1 = client.BatchV1beta1Api()
body = {"spec": {"schedule": "@daily"}}
ret = v1.patch_namespaced_cron_job(
    namespace="default", name="my-cronjob", body=body
)
print(ret)

Upvotes: 0

You can update only the selected field of resourse by patching it

patch -h                     
Update field(s) of a resource using strategic merge patch, a JSON merge patch, or a JSON patch.           

JSON and YAML formats are accepted.

Please refer to the models in
https://htmlpreview.github.io/?https://github.com/kubernetes/kubernetes/blob/HEAD/docs/api-reference/v1/definitions.html
to find if a field is mutable.

As provided in comment for ref :

kubectl patch cronjob my-cronjob -p '{"spec":{"schedule": "42 11 * * *"}}'

Also, in current kubectl versions, to launch a onetime execution of a declared cronjob, you can manualy create a job that adheres to the cronjob spec with

kubectl create job --from=cronjob/mycron

Upvotes: 38

SmCaterpillar
SmCaterpillar

Reputation: 7020

The more recent versions of k8s (from 1.10 on) support the following command:

$ kubectl create job my-one-time-job --from=cronjobs/my-cronjob

Source is this solved k8s github issue.

Upvotes: 18

Shushu
Shushu

Reputation: 792

I have a friend who developed a kubectl plugin that answers exactly that !
It takes an existing cronjob and just create a job out of it.
See https://github.com/vic3lord/cronjobjob
Look into the README for installation instructions.

Upvotes: 0

Related Questions