'How to trigger Github workflows on 'link Issue to PR'?

I would like a workflow to trigger on an Issue once it is linked to a PR but it doesn't seem like this option is provided by github. Does anyone have a workaround for this?



Solution 1:[1]

I came across this question yesterday and decided to refactor a solution that has been implemented in one of my projects, and came up with a GitHub Action for this: https://github.com/marketplace/actions/validate-issues-over-pull-requests

You can create a new workflow with the following content:

name: PR has a valid Issue?

on:
  pull_request_target:
    types: [ edited, synchronize, opened, reopened ]

jobs:
  checker:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v2
      
      - name: Issue Validator
        uses: HarshCasper/[email protected]
        id: validator
        with:
          prbody: ${{ github.event.pull_request.body }}
          prurl: ${{ github.event.pull_request.url }}

Based on the steps.validator.outputs.valid value (which can be either 1 when an issue is linked or 0 when an issue will not be linked), you can trigger a workflow of your choice.

Right now, it will work if the PR author has explicitly mentioned Fixes #XYZ or Resolves #XYZ in the PR body. Explicitly linking an issue to a Pull Request is not supported as of now.

If you wish some action to be made on an Issue, like labeling, you can use the GitHub's CLI gh utility for this purpose. If there is any specific feature you would like to have, I would be happy to work on it!

Solution 2:[2]

There isn't a specific trigger to achieve it but it should be doable by combining the event triggers.

on:
  pull_request:
    types: [ edited, labeled ]
    branches:    
      - main
  issue:
    types:
      - opened
      - labeled
   

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Harsh Mishra
Solution 2 Shashank Sinha