LoginSignup
16
5

More than 1 year has passed since last update.

GitHub Actionsでyarnのキャッシュを利用してCI高速化

Last updated at Posted at 2021-01-23

コメントいただいた通り、2021年7月にactions/setup-nodeがキャッシュ機能を実装したので、そちらを使う方が良さそうです。

目的

GitHub Actionsのワークフローの中でyarn installしている場合に、毎度時間がかかっているのを、公式のキャッシュ機能(actions/cache@v2)を使って高速化したい。

https://github.com/actions/cache
https://github.com/actions/cache/blob/main/examples.md#node---yarn

公式に記載されているymlの書き方

github/workflows/*.yml
on:
  {トリガー}:

jobs:
  <job_id>:
    name: <job_name>
    runs-on: ubuntu-latest

    steps:
      - name: Get yarn cache directory path
        id: yarn-cache-dir-path
        run: echo "::set-output name=dir::$(yarn cache dir)"

      - uses: actions/cache@v2
        id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
        with:
          path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
          key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
          restore-keys: |
            ${{ runner.os }}-yarn-

      - name: Install Dependencies
        if: steps.yarn-cache.outputs.cache-hit != 'true'
        run: /install.sh # ここでyarn installを実行

      # 以下は説明のために付け足し
      - name: Build
        run: yarn run build

Actionを実行すると

actions/cache@v2ステップのログには以下のように出力される。
何やらキャッシュがrestoreされているように見える。

Run actions/cache@v2
Received 168279738 of 180862650 (93.0%), 160.5 MBs/sec
Received 180862650 of 180862650 (100.0%), 145.7 MBs/sec
Cache Size: ~172 MB (180862650 B)
/usr/bin/tar --use-compress-program zstd -d -xf /home/runner/work/_temp/5e202deb-23fd-4213-a874-5021dc5c81f4/cache.tzst -P -C /home/runner/work/myproject/myproject
Cache restored from key: Linux-yarn-950b3c9910c22cfae7c86bc34041990748e7bee522be954b49cf1c409649ba29

そして、if: steps.yarn-cache.outputs.cache-hit != 'true'によって、キャッシュが存在する場合yarn installがスキップされている。

が、後続のyarn buildでエラーとなる。以下の例はAngularのngコマンドがないというエラー。
つまりキャッシュのrestoreがうまくできていない。

$ ng build --configuration=development --aot
/bin/sh: 1: ng: not found
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
error Command failed with exit code 127.
Error: Process completed with exit code 127.

解決方法

if: steps.yarn-cache.outputs.cache-hit != 'true' を削除して、yarnに--prefer-offlineオプションをつければ良い。
これはローカルキャッシュがある場合はそれを使い、なければネットワークからダウンロードするというオプション。

github/workflows/*.yml
      - name: Install Dependencies
        # if: steps.yarn-cache.outputs.cache-hit != 'true'
        run: yarn install --prefer-offline

参考:https://stackoverflow.com/questions/61010294/how-to-cache-yarn-packages-in-github-actions/62244232#62244232

16
5
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
5