【问题标题】:Gitlab CI/CD cache expires and therefor build failsGitlab CI/CD 缓存过期,因此构建失败
【发布时间】:2022-12-05 05:54:45
【问题描述】:

我在 typescript 中获得了 AWS CDK 应用程序,并且有 2 个阶段的非常简单的 gitlab CI/CD 管道,它负责部署:

image: node:latest

stages:
  - dependencies
  - deploy

dependencies:
  stage: dependencies
  only:
    refs:
      - master
    changes:
      - package-lock.json
  script:
    - npm install
    - rm -rf node_modules/sharp
    - SHARP_IGNORE_GLOBAL_LIBVIPS=1 npm install --arch=x64 --platform=linux --libc=glibc sharp
  cache:
    key:
      files:
        - package-lock.json
    paths:
      - node_modules
    policy: push

deploy:
  stage: deploy
  only:
    - master
  script:
    - npm run deploy
  cache:
    key:
      files:
        - package-lock.json
    paths:
      - node_modules
    policy: pull

npm run deploy 只是 cdk 命令的包装器。

但出于某种原因,有时会发生 node_modules 的缓存(可能)过期 - 只是 deploy 阶段无法获取它,因此 deploy 阶段失败:

Restoring cache
Checking cache for ***-protected...
WARNING: file does not exist                       
Failed to extract cache

我检查了缓存名称是否与之前在 dependencies 阶段运行的最后一个管道中构建的缓存名称相同。

我想它确实发生了,因为这个 CI/CD 经常几个星期都没有运行,因为我很少为那个回购做出贡献。我试图寻找根本原因,但惨遭失败。我非常理解缓存会在一段时间后过期(从我默认发现的 30 天开始),但我希望 CI/CD 通过运行 dependencies 阶段从中恢复,尽管事实上 package-lock.json 没有更新.

所以我的问题很简单“我错过了什么?我对 Gitlab 的 CI/CD 中的缓存的理解完全错误吗?我必须打开一些功能切换器吗?”

基本上我的最终目标是尽可能多地跳过 node_modules 部分的构建,但即使我几个月没有运行管道也不会在不存在的缓存上失败。

【问题讨论】:

    标签: node.js typescript gitlab-ci aws-cdk gitlab-ci.yml


    【解决方案1】:

    缓存只是一种性能优化,但是是not guaranteed to always work。您对缓存可能过期的预期很可能是正确的,因此您需要在部署脚本中进行回退。

    您可以做的一件事是将依赖项作业更改为:

    • 始终运行
    • 推送和拉取缓存
    • 如果找到缓存,则将作业短路。

    例如。是这样的:

    dependencies:
      stage: dependencies
      only:
        refs:
          - master
        changes:
          - package-lock.json
      script:
        - |
          if [[ -d node_modules ]]; then
            exit 0
          fi
        - npm install
        - rm -rf node_modules/sharp
        - SHARP_IGNORE_GLOBAL_LIBVIPS=1 npm install --arch=x64 --platform=linux --libc=glibc sharp
      cache:
        key:
          files:
            - package-lock.json
        paths:
          - node_modules
    

    另见this related question

    如果您想避免旋转不必要的作业,那么您还可以考虑合并依赖项和部署作业,并在组合作业中采用与上述类似的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-07
      • 2018-07-24
      • 1970-01-01
      • 2020-08-09
      • 2017-02-28
      • 1970-01-01
      • 2020-01-23
      相关资源
      最近更新 更多