Automatically Rerun Failed GitHub Actions Workflows

 
 
  • Gérald Barré

GitHub Actions doesn't provide a built-in way to rerun a run automatically. If you have some flakiness in your jobs, this can be a pain as you have to rerun the workflow manually.

Hopefully, you can use the workflow_run event to trigger a new workflow when a previous one fails. This allows you to rerun the failed workflow automatically.

Note that the following sample workflow will only rerun the failed workflow if it is the first attempt. If you want to rerun all attempts, you can remove the github.event.workflow_run.run_attempt == 1 condition. Also, it checks for a specific exit code (1) to determine if the workflow failed. You can adjust this condition based on your needs.

.github/workflows/retry.yaml (YAML)
name: retry
on:
  workflow_run:
    workflows: ["**"]
    types:
      - completed
    branches:
      - main

defaults:
  run:
    shell: pwsh

jobs:
  retry:
    runs-on: ubuntu-latest
    permissions:
      actions: write # Retry actions
      checks: read   # Get info about the run
    steps:
      - name: retry
        if: ${{ github.event.workflow_run.conclusion == 'failure' && github.event.workflow_run.run_attempt == 1 }}
        run: |
              # Get info about the run
              $output = gh run view --repo "${{ github.event.repository.full_name }}" "${{ github.event.workflow_run.id }}"
              $output

              # Rerun the failed workflow if needed
              if ($output -match "Process completed with exit code 1") {
                gh run rerun "${{ github.event.workflow_run.id }}" --repo "${{ github.event.repository.full_name }}"" --failed
              }
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

Note that you will still get a notification for the failed workflow, but you won't have to rerun it manually.

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub