재형이의 성장통 일지
  • Unity와 .NET을 위한 Git Actions 기반 CI 환경 및 Google Drive API 연동하기
    2024년 01월 20일 00시 22분 03초에 업로드 된 글입니다.
    작성자: 재형이
    반응형
    • 최근에 게임을 제작하고 있는 친구에게서 부탁을 하나 받게 되었다.
    • 현재 게임을 개발하고 있는데 아직 개발 초기 단계라서 CI까지만 구현해줄 수 있냐고 말이다.
    • Git Actions 같은 경우에는 예전에 국비지원을 받을 때 팀프로젝트에서 사용한 적이 있기도 하고, 규모가 엄청 큰 프로젝트는 아니었기 때문에 Git Actions로 구현해보기로 결정하였다 ++ 깃허브를 사용하고 있기도 하고😊

     


     

    • 서버랑 클라이언트를 각각 따로 구현했기 때문에 두가지 프로젝트를 CI 환경으로 구현하게 되었다. 자세한 코드는 친구와의 의리상 공개할 수 없습니다

    1. Git Actions로 Unity 프로젝트 CI 환경 구현하기

    • 일단 Unity로 구현한 프로젝트는 친구로부터 받았다.

    1-1. 깃 환경 구현하기

    # git 환경 초기화
    git init
    
    # 깃허브 주소랑 원격으로 연결하기, 인증은 알아서 해주세용
    git remote add main 깃허브주소
    
    # 깃 레포지토리 pull 해오기
    git pull
    
    # 하면 아마 다음과 같은 오류가 나실 겁니다.
    remote: Counting objects: 140, done. 
    remote: Compressing objects: 100% (137/137), done.
    remote: Total 140 (delta 7), reused 121 (delta 2) Receiving objects: 100% (140/140), 4.98 MiB | 6.56 MiB/s, done. Resolving deltas: 100% (7/7), done. 
    From 깃주소
    * [new branch]      main     -> origin/main
    There is no tracking information for the current branch. 
    Please specify which branch you want to merge with. 
    See git-pull(1) for details.      
    
        git pull <remote> <branch>  
    
    If you wish to set tracking information for this branch you can do so with:
    
        git branch --set-upstream-to=origin/<branch> main
        
    # 해당 명령어를 실행해보자
    git branch --set-upstream-to=origin/main main
    
    # git pull 다시 해보기
    git pull
    
    # 깃허브 레포지토리가 제대로 pull이 되었다

    1-2. Unity 관련 파일 .gitignore에 추가해서 깃허브에 안 올라가게 하기

    https://gitignore.io 

     

    gitignore.io

    Create useful .gitignore files for your project

    www.toptal.com

    • 위 주소에 들어가서 Unity를 검색해보면 .gitignore에 추가할 내용들을 보여준다.
    • ctrl+c,v로 .gitignore에 넣어주자!

    1-3. Unity CI 환경 구현을 위해 라이센스 발급하기

    https://game.ci/docs/github/activation/

     

    Activation | GameCI

    All actions use a Unity installation, which needs to be activated.

    game.ci

    1. 로컬 컴퓨터에 Unity Hub 설치하기
    2. CI에 사용된 Unity 계정으로 Unity Hub에 로그인하기
    3. 개인 라이선스 활성화하기

    Unity Editor는 설치해도 되고 안해도 된다 필자는 Unity로 작업할게 아니라서 Skip 했다

    • 저기서 라이센스를 발급하면 된다.

    4. 운영 체제에 따라 Unity 라이선스 파일 찾기
       - Windows: C:\ProgramData\Unity\Unity_lic.ulf
       - Mac: /Library/Application Support/Unity/Unity_lic.ulf
       - Linux: ~/.local/share/unity3d/Unity/Unity_lic.ulf
    5. GitHub에서 Secrets 설정하기

     

    • 여기서 Secrets를 생성하면 된다.
      1. UNITY_LICENSE : Unity_lic.ulf 내용 그대로 복사해서 추가
      2. UNITY_EMAIL : Unity 로그인에 사용된 이메일 주소 추가
      3. UNITY_PASSWORD : Unity 로그인에 사용된 비밀번호 추가
    • SA_KEY랑 FOLDER_ID는 추후에 추가할 것이니 아직 하지마세요!

    6. 라이센스 발급한 곳에서 return을 누르게 되면 Unity_lic.ulf 파일이 사라지게 됩니다. 다만, 해당 파일을 Secrets에 등록을 해두었다면 그대로 사용할 수 있습니다. 보안을 위해 Return해서 없애주자.

    1-4. 빌드된 파일 자동으로 구글 드라이브에 올리기

    • 친구가 빌드가 된 파일이 자동으로 구글 드라이브 공유폴더에 올라가게 해주었으면 좋겠다고 했기 때문에 구글링을 하다가 해당 링크를 찾게 되었다.

    https://github.com/marketplace/actions/google-drive-upload-git-action

     

    google-drive-upload-git-action - GitHub Marketplace

    Upload files to Google Drive

    github.com

    얼굴 부담쓰;;

    • 구글 드라이브에 올리기 위해서는 API 키를 발급해야 한다
    • 그러기 위해서 우리 대신 파일을 올려줄 서비스 계정을 먼저 만들어주자!!
    • (만약 프로젝트가 없다면 하나 만들어서 진행하면 된다)

    https://console.cloud.google.com/apis/credentials

     

    Google 클라우드 플랫폼

    로그인 Google 클라우드 플랫폼으로 이동

    accounts.google.com

    서비스 계정 만들기!

    • 서비스 계정을 만들고 키를 json 파일로 발급해서 저장해두자

    • 그 후에 API 라이브러리에 들어가서 Google Drive API를 검색해서 활성화를 시켜주자

    • 공유할 폴더를 드라이브에 생성해준 후에 위에서 생성한 서비스 계정이 접근할 수 있도록 권한을 설정해주자

    • 저기에 서비스 계정의 이메일을 편집자로 추가해주면 된다 (서비스 계정 관리 들어가면 확인 가능)
    • 이제 위에서 추가하지 않았던 FOLDER_ID와 SA_KEY를 추가해주자
      1. FOLDER_ID : 밑에 링크 확인
      2. SA_KEY : 위에서 생성했던 json 키파일의 내용을 base64로 인코딩해서 넣어주자

     
    https://ploi.io/documentation/database/where-do-i-get-google-drive-folder-id

     

    Where do I get Google Drive folder ID?

    To be able to specify where your backups should be stored, Google Drive requires you to enter an ID. (It does not work with 'folder names')Getting thi...

    ploi.io

    https://www.base64encode.org/ko/

     

    Base64 인코딩 및 디코딩 - 온라인

    Base64 형식으로 인코딩해보세요. 아니면 다양한 고급 옵션으로 디코딩해보세요. 저희 사이트에는 데이터 변환하기에 사용하기 쉬운 온라인 도구가 있습니다.

    www.base64encode.org

    1-5. Git Actions 작업 환경 만들기

    • 아까 git pull 했던 디렉토리에서 .github/workflows/main.yml 를 만들어주자 (github 앞에 . 이 있어야 한다)
    name: Build project
    
    on:
      push:
        branches: [ main ]
    
    jobs:
      buildForAllSupportedPlatforms:
        name: Build for ${{ matrix.targetPlatform }}
        runs-on: ubuntu-latest
        strategy:
          fail-fast: false
          matrix:
            targetPlatform:
              - StandaloneWindows # Build a Windows standalone. If you want Win64? Try StandaloneWindows64
        steps:
          - uses: actions/checkout@v4
            with:
              fetch-depth: 0
              lfs: true
          - uses: actions/cache@v3
            with:
              path: Library
              key: Library-${{ matrix.targetPlatform }}
              restore-keys: Library-
          - if: matrix.targetPlatform == 'Android'
            uses: jlumbroso/free-disk-space@v1.3.1
          - uses: game-ci/unity-builder@v4
            env:
              UNITY_LICENSE: ${{ secrets.UNITY_LICENSE }}
              UNITY_EMAIL: ${{ secrets.UNITY_EMAIL }}
              UNITY_PASSWORD: ${{ secrets.UNITY_PASSWORD }}
            with:
              targetPlatform: ${{ matrix.targetPlatform }}
          - name: Archive files
            run: |
              sudo apt-get update
              sudo apt-get install zip
              zip -r //원하는 파일 이름.zip build/${{ matrix.targetPlatform }}
          - name: Upload to gdrive
            uses: adityak74/google-drive-upload-git-action@main
            with:
              credentials: ${{ secrets.SA_KEY }}
              filename: //원하는 파일 이름.zip
              folderId: ${{ secrets.FOLDER_ID }}
              overwrite: "true" # optional boolean
    • 그러고 git push를 해주자. 그러면 자동으로 빌드가 진행되고 빌드된 파일이 구글 드라이브 공유 폴더에 올라간다
    • 만약에 without workflow scope 에러가 나온다면 
    refusing to allow a Personal Access Token to create or update workflow `.github/workflows/mail.yml` without `workflow` scope
    • 위 에러는 Git Actions workflow가 레포지토리에 접근할 수 있는 권한이 없어서 발생하는 에러입니다.
    • 토큰을 발행해서 workflow한테 권한을 줍시다.

    • Settings → Developer Settings (맨 밑에 있음) → Personal Access Tokens → workflow 체크

    • 그리고 발급 받은 토큰으로 깃에 로그인한 후에 git push 명령어를 실행해주면 된다

    2. Git Actions로 .Net 프로젝트 CI 환경 구현하기

    • 닷넷 프로젝트 CI 환경 구현하는 것도 위에서 Unity 설정 부분이랑 main.yml만 다르고 나머지는 같다
    name: .NET Core Build
    
    on:
      push:
        branches: [ main ]
    
    jobs:
      build:
        runs-on: windows-latest
    
        steps:
        - uses: actions/checkout@v2
    
        - name: Set up .NET Core 3.1
          uses: actions/setup-dotnet@v1
          with:
            dotnet-version: '3.1' # Specify the .NET Core version
    
        - name: Restore dependencies
          run: dotnet restore
    
        - name: Build
          run: dotnet build --configuration Release --no-restore
    
        - name: Test
          run: dotnet test --no-restore --verbosity normal
    
        - name: Publish
          run: dotnet publish --configuration Release --no-restore --output publish
    
        - name: Zip the build output
          run: Compress-Archive -Path publish/* -DestinationPath //원하는 파일이름.zip
    
        - name: Upload a file to Google Drive
          uses: willo32/google-drive-upload-action@master
          with:
            target: //원하는 파일이름.zip
            credentials: ${{ secrets.SA_KEY }}
            parent_folder_id: ${{ secrets.FOLDER_ID }}
            overwrite: "true"

    마무리

    • 처음에 로컬에서 Git Actions로 작업할 때는 문제가 생기지 않았었는데 친구 컴퓨터에서 진행을 하다보니 workflows scope 에러가 나와서 처음에 당황했었다
    • 생각해보니 나는 예전에 팀프로젝트를 하면서 Git Actions Workflow에 접근 권한을 이미 부여한 뒤였기 때문에 문제가 발생하지 않았던 것이었다;;
    • 친구 깃허브로 토큰을 발행해서 로그인할 수 있게 등록한 후에 문제를 해결하였고 친구가 굉장히 흡족하였다ㅎㅎ

    오랜만에 뿌듯~^^

    반응형
    댓글