GitLab分支间缓存共享问题:合并后Job C无法读取缓存
问题原因
GitLab共享运行器的缓存是节点本地存储的,合并请求(MR)流水线与合并后目标分支的流水线是完全独立的两个流水线,大概率会分配到不同的共享运行器节点上,因此分支流水线无法读取MR流水线在其他节点生成的缓存。另外,你的install_dependencies Job仅在MR事件中触发,合并后目标分支的流水线不会执行这个Job,自然也不会生成新的缓存,导致test2(即你说的Job C)找不到依赖。
解决方案
下面提供几种可行的解决方式,按需选择:
方式1:让目标分支流水线也执行依赖安装Job
修改install_dependencies的rules,使其在MR事件和目标分支(branch-foo)的流水线中都运行,确保分支流水线能生成自己的缓存:
install_dependencies: stage: install_dependencies cache: key: somekeyvalue1234 paths: - node_modules/ policy: push script: - npm ci rules: - if: '$CI_PIPELINE_SOURCE == "merge_request_event"' - if: '$CI_COMMIT_BRANCH == "branch-foo"'
方式2:使用依赖锁文件生成缓存Key
将缓存Key与package-lock.json的内容绑定,只要依赖锁文件不变,所有流水线(无论是MR还是分支)都能复用缓存,同时确保install_dependencies在缓存未命中时运行:
cache: key: files: - package-lock.json paths: - node_modules/ policy: pull install_dependencies: stage: install_dependencies cache: key: files: - package-lock.json paths: - node_modules/ policy: push script: - npm ci rules: - if: '$CI_PIPELINE_SOURCE == "merge_request_event"' - if: '$CI_COMMIT_BRANCH == "branch-foo"' # 可选:当缓存不存在时自动触发该Job - if: '$CI_CACHE_MISS == "true"'
方式3:改用工件(Artifacts)传递依赖
如果必须复用MR生成的依赖,可以将node_modules作为工件上传,分支流水线下载使用。注意:这种方式需要确保MR的工件未过期,且分支流水线能访问到MR的工件:
install_dependencies: stage: install_dependencies script: - npm ci rules: - if: '$CI_PIPELINE_SOURCE == "merge_request_event"' artifacts: paths: - node_modules/ expire_in: 1 day # 设置合理的过期时间 test2: stage: test2 script: - npm run test2 rules: - if: '$CI_COMMIT_BRANCH == "branch-foo"' dependencies: - install_dependencies
内容的提问来源于stack exchange,提问作者user3417586
相关产品推荐
相关产品推荐

