githubgithub-actionsworkflow-dispatch

How to trigger github action when PR is merged and Workflow dispatch?


I was trying to implement github actions when PR is merged. It also had a part of workflow dispatch.

name: Deploy to DEV
on:
  push:
    branches:
      - dev
    paths-ignore:
      - '.github/**'
  workflow_dispatch:
jobs:
  Deploy-to-Dev:
    if: github.event.pull_request.merged == true
    runs-on: ubuntu-22.04

So what i wanted to know was will Deploy-t0-Dev run or skips? If i trigger from workflow dispatch? I currently couldn't test it due to client requirements. Thanks


Solution

  • For readability and semantics sake, you can use pull_request event trigger instead of push.

    Among others, pull_request event has closed activity type:

    When a pull request merges, the pull request is automatically closed.

    And to check if the action is triggered by workflow_dispatch event, you can use GITHUB_EVENT_NAME environment variable.

    GITHUB_EVENT_NAME: The name of the event that triggered the workflow. For example, workflow_dispatch

    reference

    Your code would like this:

    name: Deploy to DEV
    on:
      workflow_dispatch: {}
    
      pull_request:
        branches:
          - dev
        paths-ignore:
          - '.github/**'
        types:
          - closed
    
    jobs:
      Deploy-to-Dev:
        if: github.event_name == 'workflow_dispatch' || github.event.pull_request.merged == true
        runs-on: ubuntu-22.04
        steps:
        - run: |
            echo The PR was merged
    

    Example code snippet reference

    Above workflow runs either when pull request is merged or when workflow is triggered manually via workflow_dispatch event.