Reputation: 671
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!"
Upvotes: 26
Views: 13072
Reputation: 766
A simple way to do this is by using Environment Protection Rules.
production
by going to Settings > Environmentsproduction
, you will find the topmost section of Deployment Branches
on clicking on production
in the list of environments.All Branches
. You can select either Protected branches
or Selected branches
with a matching pattern.Add this environment to your workflow file under jobs like:
name: A test workflow title
on:
push:
workflow_dispatch:
jobs:
print-hello-world:
runs-on: ubuntu-20.04
environment: production
steps:
- name: Print hello world
run: echo "Hello world!"
Upvotes: 7
Reputation: 671
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:
...
Upvotes: 19