Github actions: Post comment to PR workflow that triggered the current workflow

Viewed 1196

I have two workflows, the first one runs a build script and generates an artifact. The first one is triggered when a pull request is created like this:

name: build
on:
  pull_request:
    types: [opened, edited, ready_for_review, reopened]

The second flow runs when the first is done, by using the workflow_runtrigger like this:

on: 
  workflow_run:
    workflows: ["build"]
    types:
      - "completed"

The second flow has to be separate and run after the first one. When done it is supposed to post a comment on the PR that triggered the first workflow, but I am unable to find out how.

According to the Github Action Docs this is one of the typical use cases, as per this qoute:

 For example, if your pull_request workflow generates build artifacts, you can create 
 a new workflow that uses workflow_run to analyze the results and add a comment to the
 original pull request.

But I can't seem to find out how. I can get the first workflow's id in the 2nd workflow's context.payload.workflow_run.id, but workflow_run should also have about the pull request, but they`re empty.

What am I doing wrong, and where can I find the necessary info to be able to comment on my created pull request?

1 Answers

You're not doing anything wrong, it's just that the Pull Request datas from the first workflow are not present in the Github Context of the second workflow.

To resolve your problem, you could send the Pull Request datas you need from the first workflow to the second workflow.

There are different ways to do it, for example using a dispatch event (instead of a workflow run), or an artifact.

For the artifact, it would look like something as below:

In the FIRST workflow, you get the PR number from the github.event. Then you save that number into a file and upload it as an artifact.

      - name: Save the PR number in an artifact
        shell: bash
        env:
          PULL_REQUEST_NUMBER: ${{ github.event.number }}
        run: echo $PULL_REQUEST_NUMBER > pull_request_number.txt

      - name: Upload the PULL REQUEST number
        uses: actions/upload-artifact@v2
        with:
          name: pull_request_number
          path: ./pull_request_number.txt

In the SECOND workflow, you get the artifact and the Pull Request number from the FIRST workflow, using the following GitHub Apps:

      - name: Download workflow artifact
        uses: dawidd6/action-download-artifact@v2.11.0
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          workflow: <first_workflow_name>.yml
          run_id: ${{ github.event.workflow_run.id }}

      - name: Read the pull_request_number.txt file
        id: pull_request_number_reader
        uses: juliangruber/read-file-action@v1.0.0
        with:
          path: ./pull_request_number/pull_request_number.txt

      - name: Step to add comment on PR
        [...]
Related