Automatically Rerun Failed GitHub Actions Workflows

 
 
  • Gérald Barré

GitHub Actions does not provide a built-in way to automatically rerun a failed workflow. If your jobs suffer from flakiness, this requires manual intervention every time.

Fortunately, you can use the workflow_run event to trigger a new workflow whenever a previous one fails, allowing it to rerun automatically.

The sample workflow below only reruns the failed workflow on the first attempt. To allow reruns on subsequent attempts as well, remove the github.event.workflow_run.run_attempt == 1 condition. It also checks for a specific exit code (1) to determine whether the workflow failed; 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 }}

You will still receive a notification for the failed workflow, but you won't need to rerun it manually.

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

Follow me:
Enjoy this blog?