0

When using GitHub Actions, is it possible to use a variable for the branch name?

I want to specify the branch name in on > push > branches, but I also want to use it later on in my job, so I am just trying to avoid duplication.

I am using this setup:

name: 'Build and deploy'

on:
  push:
    branches:
      - my-branch
  pull_request:
    branches:
      - my-branch
  workflow_dispatch:

env:
  GITHUB_BRANCH: 'my-branch'

Doing the following gets marked as an error:

on:
  push:
    branches:
      - ${{ env.GITHUB_BRANCH }} # Unrecognized named-value: env
  pull_request:
    branches:
      - ${{ env.GITHUB_BRANCH }} # Unrecognized named-value: env
  workflow_dispatch:

Is there a way to achieve this?

Ben
  • 15,938
  • 19
  • 92
  • 138
  • Does this answer your question? [How to get the current branch within Github Actions?](https://stackoverflow.com/questions/58033366/how-to-get-the-current-branch-within-github-actions) – TonyArra Aug 22 '23 at 16:11
  • No, it does not. I want to set and use a variable, not get the current branch. – Ben Aug 22 '23 at 17:01
  • if the event trigger is configured to only run on pushes to a certain branch then `github.ref_name` will always be equal to that branch name. – TonyArra Aug 22 '23 at 19:35
  • @TonyArra Does that also apply to pull requests? (I have updated the question) – Ben Aug 24 '23 at 09:05

1 Answers1

0

How about like this?

name: 'Build and deploy'

on:
  push:
    branches:
      - my-branch
  workflow_dispatch:

env:
  GITHUB_BRANCH: ${{ github.ref_name }}

That leaves the config in one place, so it reduces the duplication like you want. Instead of branches referencing the environment variable, the environment variable references the branch, but you still have the branch defined in just one place.

Shawn
  • 8,374
  • 5
  • 37
  • 60
  • Nice idea, but will this work with pull requests? (I have updated the question) – Ben Aug 24 '23 at 09:03
  • The updated question is something different than what it was when I answered. I question why you would want to trigger on both pull requests and pushes to the same branch? Usually those are triggered on _different_ branches--where a pull request is made to pull changes from one branch into another. So while the updated question changes things in an theoretical way, in typical usage scenarios I think the branch names will be different anyway. Otherwise, a PR that triggers a run will occur after a push has already triggered a run on the same code--which would be redundant. – Shawn Aug 24 '23 at 14:50