배워서 남 주자

PR에 빌드 에러 발생시 github-actions bot이 자동으로 코멘트 달게 하기

미래에서 온 개발자 2024. 10. 3. 21:52

자동 배포 파이프라인 중 하나로 github actions를 사용 중인데, PR 올린 코드에 대해 빌드 에러가 있는지 확인해 주는 일종의 checker를 yaml로 작성했다. 

 

organization에 속해 있는 레포의 경우 SSH 키를 생성해야 한다. SSH key 생성 및 github에 등록 과정은 아래의 포스팅을 참고했다.

 

[Github Actions] CI - 빌드 실패 시 Pull Request 닫고 코멘트 등록하기

얼마전 회사에서 github actions로 CI를 적용하는 일을 맡게 되었다. 이전에 프로젝트에서 자동 배포용으로 github actions를 사용해 본 적은 있지만, 부끄럽게도 문서 한번 찾아보지 않고 블로그에 나와

zubetcha.tistory.com

 

name: CI Build Error Checker

on:
  pull_request:
    branches:
      - main
      - dev

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v3

      - name: Set up SSH Agent
        uses: webfactory/ssh-agent@v0.5.4
        with:
          ssh-private-key: ${{ secrets.SSH_PRIVATE_KEY }}

      - name: Cache node modules
        uses: actions/cache@v3
        id: cache
        with:
          path: node_modules
          key: npm-packages-${{ hashFiles('**/package-lock.json') }}

      - name: Install Dependencies
        if: steps.cache.outputs.cache-hit != 'true'
        run: npm install

      - name: Run build
        run: npm run build

      - name: Post error comment on failure
        if: failure()
        uses: actions/github-script@v6
        with:
          github-token: ${{ github.token }}
          script: |
            const pull_number = context.issue.number
            github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: pull_number,
              body: '❌ 빌드 실패! 로그를 확인하세요.',
            })

 

yaml 파일은 각자의 필요사항에 맞게 작성하면 될 것 같다. 위와 같이 파일 작성하면 actions에 대한 권한 설정을 해주지 않았기 때문에 실제 액션이 돌 때 다음과 같은 에러가 발생한다. 전체 에러 로그를 보면 403 에러라는 것을 알 수 있다. 

 

Error: Unhandled error: HttpError: Resource not accessible by integration

 

 

레포의 설정에서 actions에 대한 workflow permissions을 줘야 하는데, organization에 속한 레포는 organization 설정에서 먼저 권한을 줘야 한다. 조직 설정에서 쓰기 권한을 주지 않으면 개별 레포지토리에서는 권한 설정이 비활성화되어 있다. 

 

1. Organization > Settings > (왼쪽 사이드바) Actions > General

Workflow permissions에서 Read and write permissions을 선택하고 Save 버튼을 누른다. 

 

2. 레포지토리 > Settings > Actions > General 

동일하게 Workflow permissions에서 쓰기 권한 선택하고 저장해야 한다. 

 

github-actions bot이 자동으로 코멘트를 남겨준다.