2 min read | by Jordi Prats
As part of a CI/CD pipeline involving GitHub Actions we might want to be able to add a comment to the PR to notify the user about something:
name: demo_add_comment_pr on: pull_request: types: [opened, ready_for_review] push: branches: - '**' - '!main' paths: - cluster-resources/** - tests/** workflow_dispatch: (...)
We can check how we can add comments to PR (or issues) using the GitHub API.
First, we'll need to generate a JSON with the comment we want to add. To do so we can use jq to create the JSON object as follows:
JSON_DATA=$(jq --null-input --arg body "demo comment" '{ "body": $body }')
Once we have the data ready we can push it as follows to GitHub:
curl -X POST \ $GITHUB_URL \ -H "Content-Type: application/json" \ -H "Authorization: token $GITHUB_TOKEN" \ --data "${JSON_DATA}"
We can retrieve the GITHUB_URL to add it to the right Pull Request and the GITHUB_TOKEN to authenticate the request by populating these environment variables from the GitHub action definition as follows:
(...) jobs: ci: steps: (...) - name: Add comment env: GITHUB_URL: ${{ github.event.pull_request.comments_url }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} (...)
Posted on 12/12/2022