고기 대신 SW 한점/DEVOPS

GitHub Self-Hosted Runner에서 캐시를 구현하는 방법

지식한점 2023. 3. 15. 13:22
반응형
  1. Cache Action을 사용하기

GitHub에서는 캐시를 쉽게 구현할 수 있는 Cache Action을 제공합니다. 이 Action을 사용하면 원하는 디렉토리를 캐시할 수 있습니다. 캐시를 만들기 위해서는 캐시 이름과 캐시할 파일 또는 디렉토리를 지정해야 합니다. 예를 들어, 다음과 같은 형식으로 작성할 수 있습니다.

yaml

- name: Cache node_modules
  uses: actions/cache@v2
  with:
    path: ~/.npm
    key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
    restore-keys: |
      ${{ runner.os }}-node-

이 작업은 node_modules 디렉토리를  ~/.npm 경로에 캐쉬하며, 캐시 키는 패키지락의 파일의 해시 값을 사용합니다.

 

2. 자체 캐시 메카니즘 구현하기

자체 캐시 메카니즘을 구현할 수도 있습니다. 이 경우 캐시 디렉토리를 생성하고, 다음과 같이 작성 할 수 있습니다.

steps:
  - name: Cache node_modules
    run: |
      if [ -d "./node_modules" ]; then
        mv node_modules node_modules_cache
      fi
    shell: bash

  - name: Restore node_modules from cache
    run: |
      if [ -d "./node_modules_cache" ]; then
        mv node_modules_cache node_modules
      fi
    shell: bash

  - name: Install Dependencies
    run: npm install

이 작업은 node_modules 디렉코리를 node_modules_cache 디렉토리에 이동하고, 다음 작업에서 다시 원래 위치로 이동합니다.

이전 캐시가 있는 경우, 다운로드하여 사용할 수 있습니다. 이를 위해 먼저 캐시를 다운로드하는 스크립트를 작성합니다.

steps:
  - name: Download Cache
    uses: actions/cache@v2
    with:
      path: node_modules
      key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
      restore-keys: ${{ runner.os }}-node-

이 작업은 이전 캐시가 있으면 해당 캐시를 다운로드하고, 없으면 아무것도 하지 않습니다.

위의 방법 중 하나를 선택하여 캐시를 구현할 수 있습니다. Cache Action을 사용하면 쉽게 구현할 수 있지만, 자체 캐시 매커니즘을 구현하면 더 세밀한 제어가 가능합니다.

반응형