Search code examples
kubernetesinfluxdb

Run scheduled task inside Pod in Kubernetes


I have a small instance of influxdb running in my kubernetes cluster.
The data of that instance is stored in a persistent storage.
But I also want to run the backup command from influx at scheduled interval.

influxd backup -portable /backuppath

What I do now is exec into the pod and run it manually.
Is there a way that I can do this automatically?


Solution

  • This is the solution I have used for this question

    apiVersion: v1
    kind: ConfigMap
    metadata:
      name: cm-backupscript
      namespace: influx
    data:
      backupscript.sh: | 
        #!/bin/bash
        echo 'getting pod name'
        podName=$(kubectl get pods -n influx  --field-selector=status.phase==Running --output=jsonpath={.items..metadata.name})
        echo $podName
        #echo 'create backup'
        kubectl exec -it $podName -n influx -- /mnt/influxBackupScript/influxbackup.sh
        echo 'done'
    ---
    apiVersion: batch/v1beta1
    kind: CronJob
    metadata:
      name: backup-cron
      namespace: influx
    spec:
      schedule: "0 2 * * *"
      jobTemplate:
        spec:
          template:
            spec:
              affinity:
                nodeAffinity:
                  requiredDuringSchedulingIgnoredDuringExecution:
                    nodeSelectorTerms:
                    - matchExpressions:
                      - key: kubernetes.io/arch
                        operator: In
                        values:
                        - amd64
              volumes:
              - name: backup-script
                configMap:
                  name: cm-backupscript
                  defaultMode: 0777
              containers:
              - name: kubectl
                image: bitnami/kubectl:latest
                command:
                - /bin/sh
                - -c
                - /mnt/scripts/backupscript.sh
                volumeMounts:
                - name: backup-script
                  mountPath: "/mnt/scripts"
              restartPolicy: Never