How can I manually set values on a Kubernetes object using kubectl create?

4/8/2019

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?

-- soapergem
kubectl
kubernetes

1 Answer

4/8/2019

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 -
-- Rico
Source: StackOverflow