GitHub API
The GitHub CLI1 (gh) is a command-line interface to GitHub right from your terminal. Anything the gh CLI can do, you can do with it in GitHub Actions – it is pre-installed on all runners.
Let’s try automatically adding an issue comment when a label is added to the issue.2
.github/workflows/add-comment.yml
name: Add comment
1on:
issues:
types:
- labeled
jobs:
add-comment:
2 if: github.event.label.name == 'help wanted'
runs-on: ubuntu-latest
permissions:
issues: write
steps:
3 - name: Add comment
run: gh issue comment "$NUMBER" --body "$BODY"
env:
4 GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
5 GH_REPO: ${{ github.repository }}
6 NUMBER: ${{ github.event.issue.number }}
7 BODY: >
This issue is available for anyone to work on.
**Make sure to reference this issue in your pull request.**
:sparkles: Thank you for your contribution! :sparkles:- 1
- Run this workflow when an issue is labeled.
- 2
- Only run this job if the issues was labeled with “help wanted”.
- 3
-
Use the gh cli to add a comment to the issue.
$NUMBERand$BODYare filled in from the environment variables specified byenv. - 4
-
Set the
GH_TOKENenvironment variable to the defaultGITHUB_TOKENsecret3, which is automatically created by GitHub for each workflow run. This token is used by theghCLI to authenticate and comment on the issue. Permissions are limited by default4. - 5
-
The name of this repo, which is a required environment variable for
ghCLI5. - 6
- The issue number from the event that triggered this workflow run.
- 7
- The body of the comment to add. Use markdown syntax just like you would if you were typing an issue comment through the web interface.
Create an issue in your repo and add the “help wanted” label. Go the the Actions tab and see if the workflow is running. Once it completes, go back to your issue – did it create the comment like you expected?
Peruse the GitHub CLI manual. What other processes could you automate for managing issues, PRs, and projects?
Footnotes
GitHub CLI manual https://cli.github.com/manual/↩︎
This action was adapted from https://docs.github.com/en/actions/use-cases-and-examples/project-management/commenting-on-an-issue-when-a-label-is-added↩︎
GITHUB_TOKENhttps://docs.github.com/en/actions/security-for-github-actions/security-guides/automatic-token-authentication↩︎Default permissions for
GITHUB_TOKENhttps://docs.github.com/en/actions/security-for-github-actions/security-guides/automatic-token-authentication#permissions-for-the-github_token↩︎Environment variables needed by
ghcli https://cli.github.com/manual/gh_help_environment↩︎