How to set the result of shell script into arguments of Kubernetes Cronjob regularly

3/25/2019

I have trouble setting the result value of a shell script to arguments for Kubernetes Cronjob regularly.

Is there any good way to set the value refreshed everyday?

I use a Kubernetes cronjob in order to perform some daily task.

With the cronjob, a Rust application is launched and execute a batch process.

As one of arguments for the Rust app, I pass target date (yyyy-MM-dd formatted string) as a command-line argument.

Therefore, I tried to pass the date value into the definition yaml file for cronjob as follows.

And I try setting ${TARGET_DATE} value with following script. In the sample.sh, the value for TARGET_DATE is exported.

cat sample.yml | envsubst | kubectl apply -f sample.sh
apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: some-batch
  namespace: some-namespace
spec:
  schedule: "00 1 * * 1-5"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: some-container
            image: sample/some-image
            command: ["./run"]
            args: ["${TARGET_DATE}"]
          restartPolicy: Never

I expected that this will create TARGET_DATE value everyday, but it does not change from the date I just set for the first time.

Is there any good way to set result of shell script into args of cronjob yaml regularly?

Thanks.

-- i-whammy
kubernetes

1 Answer

3/25/2019

You can use init containers for that https://kubernetes.io/docs/concepts/workloads/pods/init-containers/

The idea is the following: you run your script that setting up this value inside init container, write this value into shared emptyDir volume. Then read this value from the main container. Here is example:

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: some-batch
  namespace: some-namespace
spec:
  schedule: "00 1 * * 1-5"
  jobTemplate:
    spec:
      template:
        spec:
          initContainers:
          - name: init-script
            image: my-init-image
            volumeMounts:
            - name: date
              mountPath: /date
            command:
            - sh
            - -c
            - "/my-script > /date/target-date.txt"
          containers:
          - name: some-container
            image: sample/some-image
            command: ["./run"]
            args: ["${TARGET_DATE}"] # adjust this part to read from file
            volumeMounts:
            - name: date
              mountPath: /date
          restartPolicy: Never
          volumes:
          - name: date
            emptyDir: {}
-- Grigory Ignatyev
Source: StackOverflow