How to run shell script using CronJobs in Kubernetes?

11/5/2019

I am trying to run a shell script at regular interval of 1 minute using a CronJob.

I have created following Cron job in my openshift template:

- kind: CronJob
  apiVersion: batch/v2alpha1
  metadata:
    name: "${APPLICATION_NAME}"
  spec:
    schedule: "*/1 * * * *"
    jobTemplate:
      spec:
        template:
          spec:
            containers:
            - name: mycron-container
              image: alpine:3
              imagePullPolicy: IfNotPresent

              command: [ "/bin/sh" ]
              args: [ "/var/httpd-init/croyscript.sh" ]
              volumeMounts:
              - name: script
                mountPath: "/var/httpd-init/"
            volumes:
            - name: script
              configMap:
                name: ${APPLICATION_NAME}-croyscript
            restartPolicy: OnFailure
            terminationGracePeriodSeconds: 0

    concurrencyPolicy: Replace

The following is the configmap inserted as a volume in this job:

- kind: ConfigMap
  apiVersion: v1
  metadata:
    name: ${APPLICATION_NAME}-croyscript
    labels:
      app: "${APPLICATION_NAME}"
  data:
    croyscript.sh: |
      #!/bin/sh
      if [ "${APPLICATION_PATH}" != "" ]; then
          mkdir -p /var/httpd-resources/${APPLICATION_PATH}
      fi
      mkdir temp
      cd temp 
      ###### SOME CODE ######

This Cron job is running. as I can see the name of the job getting replaced every 1 min (as scheduled in my job). But it is not executing the shell script croyscript.sh Am I doing anything wrong here? (Maybe I have inserted the configmap in a wrong way, so Job is not able to access the shell script)

-- Harshit Goel
configmap
cron
kubernetes
kubernetes-cronjob
openshift

1 Answer

11/5/2019

Try below approach

Update permissions on configmap location

            volumes:
            - name: script
              configMap:
                name: ${APPLICATION_NAME}-croyscript
                defaultMode: 0777

If this one doesnt work, most likely the script in mounted volume might have been with READONLY permissions. use initContainer to copy the script to different location and set appropriate permissions and use that location in command parameter

-- P Ekambaram
Source: StackOverflow