Limit GitHub action workflow concurrency on push and pull_request?

Viewed 2163

I would like to limit concurrency to one run for my workflow:

on:
  pull_request:
    paths:
      - 'foo/**'
  push:
    paths:
      - 'foo/**' 

concurrency:
  group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
  cancel-in-progress: true

However, I found out that for push head_ref is empty and run_id is always unique (as described here: https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#example-using-a-fallback-value)

How I can create a concurrency key that will be constant across pull_request and push events?

2 Answers

Try this configuration:

concurrency:
  group: ${{ github.head_ref || github.ref_name }} 
  cancel-in-progress: true

This will set the group always to the <branch-name>. The trick is that github.head_ref is only set when the workflow was triggered by a pull_request and it contains the value of the source branch of the PR.

GitHub Repo (especially look at Actions tab to see an example of cancelled workflow)

I am using this concurrency key for my workflows in similar case:

group: ${{ github.workflow }}-${{ github.ref }}

I wanted to limit it to have single workflow running on a single branch - I am cancelling previous runs. But this allows to have multiple runs across different branches at the same time - not sure what's your case exactly.

If you want to have one instance of workflow running across whole repository, you can just go for:

group: ${{ github.workflow }}
Related