在GitHub Actions中,当作业失败时如何保存缓存

20
我正在使用 GitHub 的 cache 动作,但我注意到如果作业失败,将不会创建缓存。根据 docs

如果作业 成功 完成,该动作将使用路径目录的内容创建一个新的缓存。

以下是我的工作流 YAML 文件的简化版本:
name: Build

on: [push]

jobs:
  deploy:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v1

      - name: Setup Node.js
        uses: actions/setup-node@master
        with:
          node-version: '10.x'

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

      - name: Restore yarn cache
        uses: actions/cache@v1
        id: yarn-cache
        with:
          path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
          key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
          restore-keys: |
            ${{ runner.os }}-yarn-

      - name: Install yarn dependencies
        run: yarn install

      - name: Build
        run: yarn build

我注意到如果我的Build步骤失败,cache后置步骤将不必要地被跳过,这会导致安装的依赖项不能被缓存。这需要随后的运行再次下载依赖项,减慢了作业的速度。
是否有一种方法可以始终缓存依赖项,即使构建步骤失败?
2个回答

22
在官方版本的操作中,如果构建失败,则无法缓存依赖项。请参见缓存操作清单中的此行:(译者注:该链接需要根据上下文补充)
runs:
  using: 'node12'
  main: 'dist/restore/index.js'
  post: 'dist/save/index.js'
  post-if: 'success()'

如果作业成功,则只运行后处理步骤。我不知道最初的原因,但是有一些已经开放的问题涉及到这个想法。在这个问题中,用户分叉该操作以将post-if更改为always(),假设您愿意运行非官方操作,这也许是您想要的。

11
官方操作中为什么不能进行配置? - secavfr

17
现在,您可以使用actions/cache/save操作在填充缓存后立即保存缓存,在任何测试(或可能导致作业失败的任何内容)运行之前。这就是问题actions/cache#92最终得以解决的方法。
steps:
  - uses: actions/checkout@v3
  .
  . // restore if need be
  .
  - name: Build
    run: /build.sh
  - uses: actions/cache/save@v3
    if: always() // or any other condition to invoke the save action
    with:
      path: path/to/dependencies
      key: ${{ runner.os }}-${{ hashFiles('**/lockfiles') }}

https://github.com/actions/cache/tree/main/save#always-save-cache


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接