Retry a job multiple times

Is there a way to retry a passed or failed job for more than once?

  • When tried from UI, I am able to retry a job by clicking retry button once but the button disappears after that. The API POST /projects/:id/jobs/:job_id/retry allows us to retry a job once but on second attempt with same project id and job id, it throws error “gitlab service doesn’t allow the action on this resource”. Is there any setting or configuration we can apply to enable retry feature multiple times?
1 Like

Hi @pravin.salgaonkar

In your .gitlab-ci.yml you want something like this:

run
     stage: run
     image: ruby:2.7
     before_script:
         - bundle install --path vendor/bundle
     script:
         - bundle exec ...
     retry: 2

to retry the job twice. There are docs for retry here.

Cheers,

Sarah

1 Like

thanks @snim2 for the reply.
Instead of just 2, can we specify some value to “retry” so that Job can be retry multiple times?

Yes; the 2 means that the job will be retried at most twice, but you could use any number (or presumably a variable)

It is mentioned in the docs than value >2 is not allowed. Also CI Lint doesn’t allow higher values. So there is no way to retry more times?

The runner sets some shell options per default within the shell so the job fails if there are errors within the script part. If I remember correctly, these are at least errexit and pipefail.

If you want to do more retries than the maximum allowed 2 and if your command fails with an exit code other than 0 you could deactivate errexit and wrap the command you want to retry in a loop. Not very nice and does only retry the command and not the full job, but it should work.

Like this for example for your bundle exec command. This would retry your bundle exec command 10 times if it fails with an exit code > 0 and also exit with 0 for the first success and with 1 if all 10 tries fail. Haven’t really tested it though :wink:

stage: run
image: ruby:2.7
before_script:
    - bundle install --path vendor/bundle
script:
    - |
      set +o errexit
      END=10
      for i in $(seq 1 $END); do
          echo "run $i time"
          bundle exec ... && exit 0
      done
      exit 1