Cover Image for Running Bash scripts in a Kubernetes CronJob

Running Bash scripts in a Kubernetes CronJob

Kubernetes CronJobs are a great way to run scheduled tasks in your cluster. In this post, we will set up a Kubernetes CronJob that runs a Bash script loaded from a ConfigMap.

Here's a basic setup:

apiVersion: batch/v1
kind: CronJob
metadata:
  name: my-cronjob
spec:
  schedule: "*/1 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: cronjob
            image: bash
            command: ["/bin/bash", "-c", "/scripts/script.sh"]
            volumeMounts:
            - name: scripts
              mountPath: /scripts
          volumes:
          - name: scripts
            configMap:
              name: my-script
              defaultMode: 0755

This CronJob is set to run every minute ("*/1 * * * *"). The main task here is to execute a Bash script stored in a ConfigMap.

ConfigMap as a script source

The Bash script we want to run is stored in a ConfigMap. ConfigMaps in Kubernetes are perfect for storing configuration data, but they can also be used for storing scripts, as we do in this simple example:

apiVersion: v1
kind: ConfigMap
metadata:
  name: my-script
data:
  script.sh: |
    #!/bin/bash
    echo "Hello, world!"

Mounting the ConfigMap as a volume

In the CronJob definition, we mount the ConfigMap as a volume under /scripts. This makes the script.sh available inside the container.

Running the script

By setting the defaultMode: 0755 in the volume definition, we ensure that the script is executable:

command: ["/bin/bash", "-c", "/scripts/script.sh"]

And that's it! With this setup, you've got a Kubernetes CronJob that runs a Bash script loaded from a ConfigMap. Perfect for automating tasks in your cluster without needing to rebuild container images just to update a script.


More posts...