biggboss2019
biggboss2019

Reputation: 300

How to auto close GitHub issue using GitHub CLI in GitHub Actions

I would like to automatically close the issue once it is created. For this I referred to Actions marketplace and this action. Currently my code in YAML file looks like below. GitHub token is saved in Actions >> Secrets sections, and it is Private repository. Every time I run below code I am receiving this error GraphQL: Could not resolve to an issue or pull request with the number of 1. (repository.issue). I do not understand why workflow is complaining about Could not resolve an issue? Any setting I need to perform in my GitHub repo for issue to be close automatically?

name: CI
on:
  issues:
    types:
      - opened
jobs:
  titlePrefixCheck:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Set repo
        run: gh repo set-default user/private-repo

      - name: Close Issue
        run: gh issue close --comment "Auto-closing issue" "1"
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

Upvotes: 0

Views: 116

Answers (2)

Azeem
Azeem

Reputation: 14587

GraphQL: Could not resolve to an issue or pull request with the number of 1. (repository.issue)

The number "1" is not a valid issue number in that repository.

The issues trigger's webhook payload has issue.number that'll give the issue number of the newly opened issue. So, you can use github.event.issue.number to refer to that.

Example:

name: close-issue-on-open

on:
  issues:
    types: [opened]

jobs:
  close-issue:
    runs-on: ubuntu-latest

    permissions:
      issues: write

    steps:
    - name: Close
      env:
        GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        REPO: ${{ github.repository }}
        ISSUE: ${{ github.event.issue.number }}
      run: gh issue close --repo "$REPO" --comment "Autoclosing issue $ISSUE" "$ISSUE"

For your described use case, the checkout step is not needed at all. You can simply specify the repository with gh issue close command using -R/--repo flag and that should be enough.

Depending on your GITHUB_TOKEN's permissions, you may need issues:write permission to make this work as specified in the above workflow. See Permissions for the GITHUB_TOKEN for more details on this. For example, in the absence of issues:write permission, you'll see an error like this:

GraphQL: Resource not accessible by integration (addComment)

and, adding this permission i.e.:

permissions:
  issues: write

should resolve this.

Upvotes: 2

biggboss2019
biggboss2019

Reputation: 300

For Future Stackoverflow reader- The way I solved my issue that I mention to Azeem in comment section was by updating Workflow permissions under Settings >> Actions >> General >> Workflow permissions from Read repository contents and packages permissions to Read and write permissions enter image description here

Upvotes: 0

Related Questions