如何在gitlab中使用"cache"?

How to use the "cache" in gitlab?

我在 gitlab 中创建了以下测试管道:

job1:
  stage: stage1
  rules:
    - if: $RUN != "run2"
      when: always
    - when: never
  script:
    - echo "Job stage1 updating file dates.txt"
    - date >> data/dates.txt
  cache:
    key: statusfiles
    paths:
      - data/dates.txt

job2:
  stage: stage2
  rules:
    - if: $RUN == "run2"
      when: always
  script:
    - echo "Running stage 2"
    - cat data/dates.txt
  cache:
    key: statusfiles
    paths:
      - data/dates.txt

我想在哪里使用gitlab的“缓存”功能。

这里我首先 运行 job1 更新文件 date.txt 并向此示例文件添加一个条目,因此它包含两行。

但是,当我 运行 单独使用 job2 的新管道时,文件仅包含一行。这些文件似乎是原始的、未修改的文件。

如何将文件“上传”或“保存”到 job1 中的缓存中,以便我可以在 job2 的稍后 运行 中使用更新后的文件?

首先测试“Share caches between jobs in the same branch”部分是否相关。

To have jobs in each branch use the same cache, define a cache with the key: >

$CI_COMMIT_REF_SLUG:
cache:
  key: $CI_COMMIT_REF_SLUG

This configuration prevents you from accidentally overwriting the cache.

在您的情况下,来自 discussion, and from "How archiving and extracting works":

stages:
  - build
  - test

before_script:
  - echo "Hello"

job A:
  stage: build
    rules:
      - if: $RUN != "run3"
    when: always
      - when: never
  script:
    - mkdir -p data/
    - date > data/hello.txt
  cache:
    key: build-cache
    paths:
      - data/
  after_script:
    - echo "World"

  job B:
    stage: test
    rules:
      - if: $RUN == "run3"
    script:
      - cat data/hello.txt
    cache:
      key: build-cache
      paths:
        - data/

By using a single runner on a single machine, you don’t have the issue where job B might execute on a runner different from job A.

This setup guarantees the cache can be reused between stages.

It only works if the execution goes from the build stage to the test stage in the same runner/machine. Otherwise, the cache might not be available.