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

Gitlab CI/CD 如何在.gitlab-ci.yml中定义可复用公共执行函数

GitLab CI 公共脚本复用正确实现方式

你之前的写法错误原因是:定义的锚点对应的是包含script字段的YAML对象,而script数组需要接收字符串类型的命令,直接插入锚点会导致YAML结构不合法,CI解析失败。

以下是两种常用的正确实现方案:

方案1:YAML锚点复用单条命令

如果公共逻辑只有单条命令,可以直接把命令定义为锚点使用:

image:
  name: hashicorp/terraform

before_script: 
  - export MYDATE=$(date "+%d/%m/%y - %H:%M:%S")

# 直接把curl命令定义为锚点
.send_message: &send_message 'curl --request POST --header "Authorization: Bearer $bearer"  --form "text=$MYDATE $msg" https://api.teams.com/v1/messages'

stages:
  - validate
  - plan

validate:
  stage: validate
  script:
    - terraform validate
    - *send_message
  variables:
    msg: "Example1"

plan:
  stage: plan
  script:
    - terraform validate
    - *send_message
  variables:
    msg: "Example2"

方案2:使用GitLab官方!reference标签复用脚本块

如果公共逻辑包含多条命令,更推荐使用GitLab原生的!reference标签,扩展性更强:

image:
  name: hashicorp/terraform

before_script: 
  - export MYDATE=$(date "+%d/%m/%y - %H:%M:%S")

# 定义隐藏的公共脚本块,支持多条命令
.send_message:
  script:  
    - echo "准备发送teams通知"
    - 'curl --request POST --header "Authorization: Bearer $bearer"  --form "text=$MYDATE $msg" https://api.teams.com/v1/messages'
    - echo "通知发送完成"

stages:
  - validate
  - plan

validate:
  stage: validate
  script:
    - terraform validate
    - !reference [.send_message, script]
  variables:
    msg: "Example1"

plan:
  stage: plan
  script:
    - terraform validate
    - !reference [.send_message, script]
  variables:
    msg: "Example2"

拓展场景:全Job后置执行公共逻辑

如果所有Job都需要在业务脚本执行完成后统一发送通知,可以把公共逻辑放到after_script中,通过extends继承即可,无需每个Job手动引用:

image:
  name: hashicorp/terraform

before_script: 
  - export MYDATE=$(date "+%d/%m/%y - %H:%M:%S")

.send_notify:
  after_script:
    - 'curl --request POST --header "Authorization: Bearer $bearer"  --form "text=$MYDATE $msg" https://api.teams.com/v1/messages'

stages:
  - validate
  - plan

validate:
  stage: validate
  extends: .send_notify
  script:
    - terraform validate
  variables:
    msg: "Example1"

plan:
  stage: plan
  extends: .send_notify
  script:
    - terraform plan
  variables:
    msg: "Example2"

内容的提问来源于stack exchange,提问作者wiwa1978

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 05:57:01