mbxzxz
mbxzxz

Reputation: 425

k8s cronjob run next command if current fails

I have a cronjob like below

apiVersion: batch/v1
kind: CronJob
metadata:
  name: foo-bar
  namespace: kube-system
spec:
  schedule: "*/30 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          serviceAccountName: foo-cleaner
          containers:
          - name: cleanup
            image: bitnami/kubectl
            imagePullPolicy: IfNotPresent
            command:
            - "bin/bash"
            - -c
            - command1;
              command2;
              command3;
            - new_command1;
              new_command2;
              new_command3;

Sometimes command2 fails, throws error and cronjob execution fails. I want to run new_command1 even if any command in previous block fails

Upvotes: 0

Views: 162

Answers (1)

Hemanth Kumar
Hemanth Kumar

Reputation: 3772

In the command section you need to pass the command and args below :

command: ["/bin/sh","-c"] args: ["command 1 || command 2; Command 3 && command 4"]

The command ["/bin/sh", "-c"] is to run a shell, and execute the following instructions. The args are then passed as commands to the shell.

In shell scripting a semicolon separates commands, and && conditionally runs the following command if the first succeeds, Grep/Pipe (||) runs command1 if it fails then runs command2 also.

As per above command it always runs command 1 if it fails or gives any error then it continues to run command2. If command3 succeeds then only it runs command4. Change accordingly in your Yaml and have a try.

Refer this Doc for cron jobs.

Upvotes: 1

Related Questions