IaC/CI CD Tool

3. Github Action (With Automate Pull Request)

Somaz 2023. 5. 23. 20:35
728x90
반응형

Overview

이번 글에서는 협업 필수 도구인 Pull Request (PR) 개념을 간단히 짚어본 뒤, 이를 GitHub Actions를 활용해 자동화하는 방법에 대해 실습과 함께 정리했다.

 

Pull Request는 협업 중인 개발자가 자신의 변경 사항을 리뷰 받고 병합 요청하기 위한 Git 기반 협업 플로우이다. 하지만, 조직의 브랜치 보호 정책이나 자동화된 변경사항 생성(workflow 등)에 따라 직접 PR을 날리는 작업을 자동화할 필요가 생긴다.

 

이를 위해 이번 글에서는 다음과 같은 내용을 다루었다.

  • Pull Request의 기본 개념과 용도
  • branch protection rules 정책 하에서 직접 PR을 날릴 수 없는 상황
  • GitHub Actions를 사용해:
    • 자동 브랜치 생성
    • 파일 생성 및 커밋
    • GitHub API를 통한 PR 요청 자동화
  • 실제 조직 환경에서의 prod 브랜치 조건부 PR 자동화 예시

 

이 과정을 통해 브랜치 보호가 설정된 환경에서 PR 자동화를 구현하는 현실적인 방법을 알아보았다.

 

 

 

출처 : https://medium.com/@urna.hybesis/pull-request-workflow-with-git-6-steps-guide-3858e30b5fa4

 

 

📅 관련 글

2023.04.27 - [IaC/CI CD Tool] - 1. Github Action이란?

2023.05.22 - [IaC/CI CD Tool] - 2. Github Action (With Syntax)

2023.05.22 - [IaC/CI CD Tool] - 3. Github Action (With Automate Pull Request)

2024.03.12 - [IaC/CI CD Tool] - 4. Github Action (With Matrix Strategy)

2024.03.12 - [IaC/CI CD Tool] - 5. Github Action (With Using jobs in a workflow & Choosing the runner for a job)

2024.03.15 - [IaC/CI CD Tool] - 6. Github Action (With Using Concurrency)

2024.05.28 - [IaC/CI CD Tool] - 7. Github Action Build and Push(with GCP Artifact Registry)

2024.05.28 - [IaC/CI CD Tool] - 7. Github Action Build and Push(with GCP Artifact Registry)

2024.06.20 - [IaC/CI CD Tool] - 8. Github Action Template 생성후 MarketPlace 등록하기

2024.11.10 - [IaC/CI CD Tool] - 9. Github Action Steps Context 활용법

2025.01.22 - [IaC/CI CD Tool] - 10. Github Action Hosted Runner 생성

 

 

 


 

 

Pull Request란?

Pull Request는 협업 중인 개발 프로젝트에서 일반적으로 사용되는 Git 기능 중 하나이다.

Pull Request는 개발자가 코드의 변경사항을 다른 사람에게 알리고 그 변경사항을 메인 코드베이스에 병합(merge)하도록 요청하는 것을 의미한다.

 

 

 

Pull Request pipeline 자동화하기

아래의 요구 사항을 반영하기 위해 먼저, 개인 GitHub에서 테스트를 해보기로 하였다.

어느날 개발자에게 아래와 같은 요청이 왔다.

"github branch protection rules 설정을 사용해서 master branch로 push하는걸 막을꺼에요. 만약에 Trigger로 인해 master branch의 있는 workflow가 동작한다면 새로운 branch를 자동으로 만들고 해당 branch에서 master branch로 PR을 날리게 자동화 시켜주세요!"

 

 

 


 

 

 

 

 

개인 GitHub 테스트

 

Git Clone 후 브랜치 생성

# 디렉토리별로 Git ssh-key를 다른걸 쓰도록 구성해 놓았다.
$ git clone git@github.com-somaz94:somaz94/test.git

$ git checkout -b test2
Switched to a new branch 'test2'

$ git push --set-upstream origin test2

 

Personal access token 생성 (PAT)

Developer settings 클릭!

 

 

Token 복사하기(Test 후 삭제하였다)

 

 

 

 

PAT secret 설정

 

 

 

 

 

 

github workflow 설정

트리거 설정까지 하면 너무 복잡하기 때문에 test2 branch에 push가 일어나면 작동하도록 설계하였다.

name: Create Pull Request

on:
  push:
    branches:
      - test2

jobs:
  create_pull_request:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v2
        with:
          fetch-depth: 0
          persist-credentials: false
          token: ${{ secrets.CICD_PAT }}

      - name: Create test.txt file
        run: echo "This is a test file" > test.txt

      - name: Commit and push test.txt file
        run: |
          git config --global user.email "somaz@gmail.com"
          git config --global user.name "somaz"
          git checkout test1
          git add test.txt
          git commit -m "Add test.txt file"
          git push https://${{ secrets.CICD_PAT }}@github.com/${{ github.repository }} test1

      - name: Create pull request
        env:
          GITHUB_TOKEN: ${{ secrets.CICD_PAT }}
        run: |
          PR_JSON=$(curl -s -X POST -H "Authorization: token $GITHUB_TOKEN" -H "Accept: application/vnd.github+json" https://api.github.com/repos/${{ github.repository }}/pulls -d '{"title": "Add test.txt file", "head": "test1", "base": "main"}')
          echo "$PR_JSON" | jq '.number'

 

$ git add .github/


$ git commit -m "ADD .github"
[test2 2b01eb5] ADD .github
 1 file changed, 33 insertions(+)
 create mode 100644 .github/workflows/pull-request.yml

 

 

 

 

github branch protection rules 설정

Protection Rule 설정

 

 

 

 

 

test2 branch push

$ git add test2

$ git commit -m "ADD test2"
[test2 daf1670] ADD test2
 1 file changed, 1 insertion(+)
 create mode 100644 test2

$ git push
Enumerating objects: 4, done.
Counting objects: 100% (4/4), done.
Delta compression using up to 16 threads
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 278 bytes | 278.00 KiB/s, done.
Total 3 (delta 1), reused 0 (delta 0)
remote: Resolving deltas: 100% (1/1), completed with 1 local object.
To github.com-somaz94:somaz94/test.git
   2b01eb5..daf1670  test2 -> test2

 

 

PR 확인!

 

 

 

 

 

 

 


 

 

 

 

 

실제 적용 GitHub 소스코드

      - name: Add & Commit & Push files
        if: ${{ steps.gen.outputs.isGenfileModified == 'true' && github.event.client_payload.ref_name != 'prod' }}
        env:
          TRIGGER_USER: ${{ github.event.sender.login }}
          BRANCH: ${{ env.BRANCH }}
          RUN_NUMBER: ${{ env.RUN_NUMBER }}
        run: |
          git config --global user.email "xxx@xxx"
          git config --global user.name "xxx"
          git add libs
          git commit -m "Update generated files by $TRIGGER_USER. Run number: ${{ env.RUN_NUMBER }}"
          git push -u origin ${{ github.event.client_payload.ref }}

      - name: Add & Commit & Push files & Pull request
        if: ${{ steps.gen.outputs.isGenfileModified == 'true' && github.event.client_payload.ref_name == 'prod' }}
        env:
          TRIGGER_USER: ${{ github.event.sender.login }}
          BRANCH: ${{ env.BRANCH }}
          RUN_NUMBER: ${{ env.RUN_NUMBER }}
          CICD_PAT: ${{ secrets.CICD_PAT }} # Add CICD_PAT from organization secrets
        run: |
          git config --global user.email "xxx@xxx"
          git config --global user.name "xxx"
  
          # Create a new branch for the changes
          git checkout -b "update-generated-files-$TRIGGER_USER-$RUN_NUMBER"
  
          git add libs
          git commit -m "Update generated files by $TRIGGER_USER. Run number: ${{ env.RUN_NUMBER }}"
          git push -u origin "update-generated-files-$TRIGGER_USER-$RUN_NUMBER"
  
          # Create a pull request using the GitHub API
          PR_JSON=$(curl -s -X POST -H "Authorization: token $CICD_PAT" -H "Accept: application/vnd.github+json" https://api.github.com/repos/$GITHUB_REPOSITORY/pulls -d '{"title":"Update generated files by '"$TRIGGER_USER"'. Run number: '"${RUN_NUMBER}"'", "head":"update-generated-files-'"$TRIGGER_USER"'-'"$RUN_NUMBER"'", "base":"'"${{ github.event.client_payload.ref }}"'"}')
          echo "$PR_JSON" | jq '.number'
  • prod 환경으로 트리거 요청이 올때만, pull request 를 요청하게 설정하였다.

 

 

 

Github Action을 활용해서 간단하게 설정할수도 있다.

https://github.com/somaz94/go-git-commit-action

 

GitHub - somaz94/go-git-commit-action: go-git-commit-action

go-git-commit-action. Contribute to somaz94/go-git-commit-action development by creating an account on GitHub.

github.com

 

 

 

 

 

 

 

 


 

 

 

마무리하며

GitHub Actions는 단순한 CI/CD 도구를 넘어 코드 협업 플로우 전반을 자동화할 수 있는 강력한 무기이다.

 

특히 Pull Request 자동화는 다음과 같은 상황에서 유용하게 쓰일 수 있다.

  • 워크플로우 결과로 생성된 파일을 PR 형태로 전달하고 싶은 경우
  • 자동화된 테스트/빌드 결과를 병합이 아닌 PR로 트래킹하고 싶은 경우
  • 브랜치 보호로 직접 Push가 제한된 상황

 

이번 실습은 GitHub API를 직접 호출하여 PR을 만드는 방식으로 구성했지만, peter-evans/create-pull-request 같은 액션을 사용해 보다 간결하게 구현할 수도 있다.

 

협업 자동화를 고민하고 있다면, 이제는 GitHub Actions와 함께 Pull Request도 자동으로 처리해보세요.

 

 

 

 


Reference

https://medium.com/@urna.hybesis/pull-request-workflow-with-git-6-steps-guide-3858e30b5fa4

 

https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/incorporating-changes-from-a-pull-request/merging-a-pull-request

 

728x90
반응형

'IaC > CI CD Tool' 카테고리의 다른 글

ArgoCD 설치 AWS & GCP  (0) 2023.08.09
4. GitLab 버전 업그레이드  (0) 2023.08.08
2. Github Action (With Syntax)  (0) 2023.05.22
1. Github Action이란?  (0) 2023.05.19
ArgoCD란?  (0) 2023.05.17