Amin Pashna
Amin Pashna

Reputation: 161

How to execute script shell in Kubernetes cronjob

I would like to run a shell script inside the Kubernetes using CronJob, here is my CronJon.yaml file :

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: hello
spec:
  schedule: "*/1 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: hello
            image: busybox
            imagePullPolicy: IfNotPresent
            command:
            - /bin/sh
            - -c
            - /home/admin_/test.sh
          restartPolicy: OnFailure

CronJob has been created ( kubectl apply -f CronJob.yaml ) when I get the list of cronjob I can see the cron job ( kubectl get cj ) and when I run "kubectl get pods" I can see the pod is being created, but pod crashes. Can anyone help me to learn how I can create a CronJob inside the Kubernetes please ?

enter image description here

enter image description here

Upvotes: 4

Views: 20624

Answers (1)

Wytrzymały Wiktor
Wytrzymały Wiktor

Reputation: 13878

As correctly pointed out in the comments, you need to provide the script file in order to execute it via your CronJob. You can do that by mounting the file within a volume. For example, your CronJob could look like this:

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: hello
spec:
  schedule: "*/1 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: hello
            image: busybox
            imagePullPolicy: IfNotPresent
            command:
            - /bin/sh
            - -c
            - /myscript/test.sh
            volumeMounts:
            - name: script-dir
              mountPath: /myscript
          restartPolicy: OnFailure
          volumes:
          - name: script-dir
            hostPath:
              path: /path/to/my/script/dir
              type: Directory

Example above shows how to use the hostPath type of volume in order to mount the script file.

Upvotes: 12

Related Questions