Gitlab CI - 如果缓存存在,如何跳过作业

Nic*_*owr 11 caching gitlab gitlab-ci yarnpkg

我的 CI 中有一份setup工作,它安装所有 npm 包并将它们存储在缓存中:

setup:
  stage: pre-build
  cache:
    untracked: true
    when: on_success
    key:
      files:
        - repo-hash
      prefix: workspace
  script:
    - yarn install --frozen-lockfile
Run Code Online (Sandbox Code Playgroud)

目前,如果 repo-hash 在两个管道之间没有更改,则作业会成功下载现有缓存,但它仍然运行yarn install --frozen-lockfile

如何更改此行为,以便如果缓存存在,则跳过此作业?

Kar*_*ple 11

现在,在基于 NPM 的 Preact 项目中,only如果 package-lock.json 发生任何更改,我将使用 gitlab-ci.yml 的功能来运行安装作业(如果没有更改,则跳过安装)。然后我的构建作业从安装作业中获取 node_modules 缓存:

install:
  stage: setup # gitlab.com shared runners are slow; don't run unless there's a reason to install
  cache:       # even a "echo 'hello world'" script would be about a 30s job, worse if queued
    key:
      files: [package-lock.json] # the key is a hash of package-lock; branches with it will use this cache :D
    paths: [node_modules] # we're not caching npm (ie `npm ci --prefer-offline --cache`) because it's slow
    policy: push # override the default behavior of wasting time downloading and unpacking node_modules
  script: [npm ci] # I believe in package-lock/npm ci's mission
  only:
    changes: [package-lock.json] # our forementioned reason to install
    refs:
      - master
      - develop
      - merge_requests

build: # uses the default behavior, which runs even if install is skipped; but not if install failed
  stage: build
  cache:
    key:
      files: [package-lock.json]
    paths: [node_modules]
    policy: pull # override the default behavior of wasting time packing and uploading node_modules
  script:
    - npm run build
  artifacts:
    paths: [build]
  only:
    changes:
      - src/**/*
      - tsconfig.json
      - preact.config.js
      - package-lock.json
    refs:
      - master
      - develop
      - merge_requests
Run Code Online (Sandbox Code Playgroud)

对于 Yarn,您只需将package-lock.json此处看到的任何内容替换为yarn.lock,然后替换npm ciyarn install --frozen-lockfile

以前,我是在构建工作中完成这一切的,如下所示(类似于此处的其他答案之一):

build:
  stage: build
  cache:
    key:
      files: [package-lock.json]
    paths: [node_modules]
  script:
    - test -d node_modules || npm ci
    - npm run build
  artifacts:
    paths: [build]
  only:
    changes:
      - src/**/*
      - tsconfig.json
      - preact.config.js
      - package-lock.json
    refs:
      - master
      - develop
      - merge_requests
Run Code Online (Sandbox Code Playgroud)

我改用了更复杂的方法,因为我认为我也将实现 npm 缓存的缓存,但我似乎无法改善任何实际安装时间 - 事情实际上变得更糟。但我还是坚持了下来,只是因为它让我能够在锁定文件未更改的情况下再挤出 20 秒的时间。我发现这两种方法都是有效的。在我的具体情况下,缓存 node_modules 减少了大约一分半钟的部署时间。


小智 9

尝试退出?

install:
  stage: install
  cache:
    key:
      files:
        - package-lock.json
      prefix: $CI_PROJECT_NAME
    paths:
      - node_modules/
  script:
    - |
      if [[ -d node_modules ]]; then
        exit 10
      fi
    - npm ci --cache .npm --prefer-offline
  allow_failure:
    exit_codes: 10
Run Code Online (Sandbox Code Playgroud)