Search code examples
github-actions

How can I prevent a GitHub action from running in parallel for the same branch, including pull requests?


I have a GitHub action. It can be triggered from a branch, from a pull request, or manually. I want to achieve the following: There must never be two instances of this action running in parallel from the same branch, including pull requests from the branch.

My best idea is to do this (pseudocode):

concurrency: {{ if github.head_ref is nonempty then github.head_ref else github.ref }}

When the job is triggered from a PR, github.head_ref contains the name of the source branch. When the job is triggered from a branch, github.ref contains the branch name. So the above expression should solve my problem, except that it is not valid GitHub action code, and I cannot figure out whether it possible to make such an expression.

Can I write an expression or combination of expressions to achieve the above? Or can I solve my root problem in some other way?


Solution

  • As suggested in the doc, in this example, you could define a fallback/default value, so try with:

    concurrency: 
      group: ${{ github.head_ref ||  github.ref }}