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

如何在GitLab CI中一次性定义函数供所有作业调用

你可以仅定义一次函数就给多个作业调用。首先需要明确:GitLab CI 的每个作业运行在独立的 shell 环境中,不同作业的环境完全隔离,直接把函数定义在某个作业的 script 块中,其他作业无法访问,你预期的写法不能实现需求,可通过以下三种方案实现:

方案1:全局 before_script(最简便,适合所有作业都需要加载函数的场景)

全局 before_script 会在所有作业的 script 执行前自动运行,把函数定义放在这里,所有作业都可以直接调用:

stages:
  - st1
  - st2
  - st3

# 全局前置脚本,所有作业都会先执行这里的代码
before_script:
  - |
    function curling() {
      echo "ip are $1"
    }

st1:
  stage: st1
  script:
    - curling "st1 测试调用"

st2:
  stage: st2
  script:
    - foo=$(curl -x socks4 ifconfig.co) # 注意curl指定代理的参数是 -x 不是 +x
    - boo=$(curl ifconfig.co)
    - |
      # 字符串比较用=,变量加双引号避免空值/空格报错
      if [ "$foo" = "$boo" ]
      then
        curling equal
      else
        curling not_equal
      fi
  when: manual
  only:
    - master
  tags: 
   - tag

st3:
  stage: st3
  script:
    - foo=$(curl -x socks5 ifconfig.co)
    - boo=$(curl ifconfig.co)
    - |
      if [ "$foo" = "$boo" ]
      then
        curling equal
      else
        curling not_equal
      fi
  when: manual
  only:
    - master
  tags: 
   - tag

方案2:YAML 锚点引用(适合只给指定作业加载函数的场景)

如果你不想给全局所有作业都加载该函数,可以把函数定义为 YAML 锚点,需要的作业手动引用即可:

stages:
  - st1
  - st2
  - st3

# 定义函数锚点
.curling_func: &curling_func
  - |
    function curling() {
      echo "ip are $1"
    }

st1:
  stage: st1
  before_script:
    *curling_func # 引用锚点,加载函数
  script:
    - curling "st1 测试调用"

st2:
  stage: st2
  before_script:
    *curling_func
  script:
    # 自定义逻辑,直接调用函数
  when: manual
  only:
    - master
  tags: 
   - tag

方案3:独立 shell 脚本(适合通用函数多、逻辑复杂的场景)

把通用函数存放到仓库内的独立脚本文件,比如 scripts/common.sh:

#!/bin/bash
function curling() {
  echo "ip are $1"
}
# 可新增其他通用函数

作业中先加载该脚本即可调用函数:

st2:
  stage: st2
  script:
    - chmod +x ./scripts/common.sh && source ./scripts/common.sh
    - foo=$(curl -x socks4 ifconfig.co)
    # 直接调用curling函数

额外简化技巧

你还可以把作业中重复的 when、only、tags 等配置也抽为通用模板,进一步减少重复代码:

# 通用作业模板
.common_job: &common_job
  when: manual
  only:
    - master
  tags:
    - tag
  before_script:
    *curling_func

st2:
  <<: *common_job # 继承模板所有配置
  stage: st2
  script:
    # 只写差异化的自定义逻辑即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 05:57:03