You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GitLab CI YAML锚点、extends及!reference失效问题排查

GitLab CI 复用脚本的正确实现方法

下面针对三种复用方式的问题,给出正确配置写法,确保touch foo.txt能在多作业多阶段执行,最终在build-job的ls -al输出中看到foo.txt。

1. YAML锚点的正确用法

常见错误

直接将锚点赋值给before_script(如&setup touch foo.txt)会触发语法错误,因为GitLab CI要求before_script必须是数组类型,而非单个字符串。

正确配置

stages:
  - build
  - test

# 定义数组类型的锚点
&setup_steps
  - touch foo.txt

build-job:
  stage: build
  before_script: *setup_steps
  script:
    - ls -al

test-job:
  stage: test
  before_script: *setup_steps
  script:
    - echo "Test job using reused script"

2. extends关键字的正确用法

常见错误

复用模板时未将脚本放在before_script或script的数组中,或者模板定义不完整,导致脚本未被继承执行。

正确配置

stages:
  - build
  - test

# 定义可继承的模板作业
.setup-template:
  before_script:
    - touch foo.txt

build-job:
  stage: build
  extends: .setup-template
  script:
    - ls -al

test-job:
  stage: test
  extends: .setup-template
  script:
    - echo "Test job using extended template"

3. !reference标签的正确用法

常见错误

未正确引用全局定义的可复用块,或者引用路径有误(GitLab 13.9+支持!reference)。

正确配置

stages:
  - build
  - test

# 定义全局可引用的块
.setup-commands:
  before_script:
    - touch foo.txt

build-job:
  stage: build
  before_script: !reference [.setup-commands, before_script]
  script:
    - ls -al

test-job:
  stage: test
  before_script: !reference [.setup-commands, before_script]
  script:
    - echo "Test job using referenced commands"

验证说明

以上三种配置执行后,build-job的script阶段执行ls -al时,都会显示已生成的foo.txt文件,实现了脚本复用的目标。

内容的提问来源于stack exchange,提问作者A. Gardner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 15:17:13