cancel previous pipelines when a new one is triggered GitHub Actions

Viewed 895

I have hit a blocker and I am sure other must have faced this issue so just checking if there is any workaround.

This is a sample Github workflow

name: Test Build
on:
  pull_request:
    types: [opened, synchronize, reopened]

jobs:
  app-1:
    runs-on: ubuntu-latest
    steps:
      - name: App-1
        run: echo "test1"
  app-2:
    runs-on: ubuntu-latest
    steps:
      - name: App-2
        run: echo "test1"

Now if I commit multiple times it will trigger multiple build which will clash with each other and fail the pipeline. Is there a way I can cancel a running build of that particular PR?

I see there is one option

concurrency: 
  group: CI-${GITHUB_REF#refs/heads/}
  cancel-in-progress: true

but I don't understand what's group means here and concurrency is not canceling or skipping but failing the build.That should not be the case. Am I missing something here?

1 Answers

You're almost there. The concurrency group is just a name which is observed by GitHub Action. We're using the following concurrency on workflow level (you can also use job level):

on:
  workflow_dispatch:
  pull_request:
      types: [opened, synchronize, reopened]

concurrency:
  group: ${{ github.ref }}
  cancel-in-progress: true

The group is set to your <ref> and if you push again on the same <ref> GitHub recognizes a newer push with a higher priority. Current running actions in the same group are getting terminated and a new one will start. You will receive the following message from GitHub Action Canceling since a higher priority waiting request for '<ref>' exists in the terminated action.

The GitHub documentation for concurrency on workflow level you can find here

Related