github-actionsworkflow-dispatchbranch-filter

Prohibit workflow dispatch from running on branches other than main


I would like to prevent GitHub Action's workflow dispatch to only work on the main branch. I've tried the following, but it doesn't work:

on:
  workflow_dispatch:
    branches: 
      - main

When I go to the Github actions screen to run the pipeline manually, I can also try to run it on the other branches. Ideally, I would like to forbid running this job (publishing) on any non-main branch.

Is there any way I can enforce this?

For reference, the pipeline is part of this YML. You can also see the publish job running on Test branch on the Actions screen.


Solution

  • You can add a if: github.ref == 'refs/heads/master' to your job that'll prevent it from running on a given branch.

    Or like if: startsWith(github.ref, 'refs/heads/release') if you want to only run on your release branches

    Example:

    jobs:
      Setup:
        runs-on: ubuntu-latest
        if: github.ref == 'refs/heads/main'
        steps:
          ...
    

    Alternatively you might also be able to use the workflow_run syntax, see https://docs.github.com/en/actions/writing-workflows/choosing-when-your-workflow-runs/events-that-trigger-workflows#limiting-your-workflow-to-run-based-on-branches