Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow manual workflow_dispatch only on specific branches?

I have a GitHub Actions workflow file, which allows a manual trigger using the workflow_dispatch event. GitHub offers a drop-down list to choose on which branch to run the workflow.

I was wondering if there is any way to limit that option to a specific branch (or specific branches).

Example of a workflow file with a workflow_dispatch:

name: A test workflow title
on:
  push:
  workflow_dispatch:
    # branches:    # *** This seems to not be supported! ***
      # - main

jobs:
  print-hello-world:
    runs-on: ubuntu-20.04
    steps:
      - name: Print hello world
        run: echo "Hello world!"
like image 584
Ohav Avatar asked Sep 06 '25 05:09

Ohav


1 Answers

Using if you can add a step to fail a job if the workflow was triggered by workflow_dispatch on specific branches.

name: A test workflow title
on:
  push:
  workflow_dispatch:

jobs:
  print-hello-world:
    runs-on: ubuntu-20.04
    steps:
      - name: Fail if branch is not main
        if: github.event_name == 'workflow_dispatch' && github.ref != 'refs/heads/main'
        run: |
          echo "This workflow should not be triggered with workflow_dispatch on a branch other than main"
          exit 1

      - name: Print hello world
        run: echo "Hello world!"

      - name: Log github context
        run: echo "${{ toJSON(github) }}"

It's also possible to skip the job by placing the negative condition in the job-level:

jobs:
  print-hello-world:
    if: github.event_name != 'workflow_dispatch' || github.ref == 'refs/heads/main'
    runs-on: ubuntu-20.04
    steps:
    ...

like image 110
Ohav Avatar answered Sep 11 '25 16:09

Ohav