Reputation: 9989
In particular, I want to set environment variables. I have a CronJob
definition that runs on a schedule, but every so often I want to invoke it manually while specifying slightly different environment variables.
I can invoke the cron job manually with this command:
kubectl create job --from=cronjob/my-cron-job my-manual-run
But that copies in all the same environment variables that are specified in the resource definition. How can I add additional, new environment variables using this create job
command?
Upvotes: 9
Views: 4212
Reputation: 91
I built on the answer from @Rico to first create the job in kubectl as a --dry-run
, then modifiy the job using jq
, then apply. This removes the need for having base JSON files and having to manage additional job metadata fields.
For example:
$ kubectl create job --from=cronjob/my-cron-job my-manual-run --dry-run -o "json" \
| jq ".spec.template.spec.containers[0].env += [{ \"name\": \"envname1\", value:\"$envvalue1\" }]" \
| kubectl apply -f -
Upvotes: 9
Reputation: 61551
Easiest to do IMO is to have a base JSON file and modify it. The output of kubectl get cronjob jobname
has a lot of other info that you don't need.
For example:
{
"apiVersion": "batch/v1",
"kind": "Job",
"metadata": {
"name": "changeme"
},
"spec": {
"template": {
"metadata": {
"labels": {
"job-name": "changeme"
}
},
"spec": {
"restartPolicy": "Never",
"containers": [
{
"command": [
"perl",
"-Mbignum=bpi",
"-wle",
"print bpi(2000)"
],
"image": "perl",
"name": "pi"
}
]
}
}
}
}
Then run something like this:
$ cat yourjobtemplate.json \
| jq '. + {metadata: {name: "mynewjobname"}}' \
| jq '.spec.template.metadata.labels |= . + {"job-name": "mynewjobname"}' \
| jq '.spec.template.spec.containers[0] |= . + {"env": [{name: "envname1", value: "envvalue1"}, {name: "envname2", value: "envvalue2"}]}' \
| kubectl apply -f -
Upvotes: 2