Ohav
Ohav

Reputation: 671

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!"

Upvotes: 26

Views: 13072

Answers (2)

Saurish Kar
Saurish Kar

Reputation: 766

A simple way to do this is by using Environment Protection Rules.

  1. Create an environment for your workflow file like production by going to Settings > Environments
  2. After creating production, you will find the topmost section of Deployment Branches on clicking on production in the list of environments.
  3. You should be able to see a button with the default option of 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!"

References:
https://docs.github.com/en/actions/deployment/targeting-different-environments/using-environments-for-deployment#environment-protection-rules

https://docs.github.com/en/actions/deployment/targeting-different-environments/using-environments-for-deployment#creating-an-environment

Upvotes: 7

Ohav
Ohav

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

Related Questions