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

如何通过GitLab API运行GitLab CI/CD中的指定任务?

实现指定任务运行的完整步骤

1. 更新.gitlab-ci.yml配置

为每个需要单独触发的任务添加规则,通过自定义变量RUN_JOBS控制任务是否执行。规则逻辑:仅当RUN_JOBS变量包含当前任务名称时,任务才会运行;未传递该变量时,默认不执行任何任务(可按需调整默认行为)。

修改后的完整配置如下:

build-job:
  stage: build
  script:
    - echo "Hello, $GITLAB_USER_LOGIN!"
  rules:
    - if: '$RUN_JOBS =~ /build-job/'
      when: always
    - when: never

test-job1:
  stage: test
  script:
    - python3 mydumbscript.py $arg1 $arg2 $arg3
  rules:
    - if: '$RUN_JOBS =~ /test-job1/'
      when: always
    - when: never

test-job2:
  stage: test
  script:
    - echo "This job tests something, but takes more time than test-job1."
    - echo "After the echo commands complete, it runs the sleep command for 20 seconds"
    - echo "which simulates a test that runs 20 seconds longer than test-job1"
    - sleep 20
  rules:
    - if: '$RUN_JOBS =~ /test-job2/'
      when: always
    - when: never

deploy-prod:
  stage: deploy
  script:
    - echo "This job deploys something from the $CI_COMMIT_BRANCH branch."
  environment: production
  rules:
    - if: '$RUN_JOBS =~ /deploy-prod/'
      when: always
    - when: never

规则说明

  • $RUN_JOBS =~ /任务名/:采用正则匹配,支持用逗号分隔多个任务(如test-job1,test-job2),只要变量中包含任务名就会执行对应任务。
  • 最后一条- when: never:确保未指定任务时,该任务不会自动运行。若需默认运行所有任务,可将此条改为- when: always,并调整第一条规则逻辑。

2. 配置触发变量文件(variables.json)

在variables.json中添加RUN_JOBS变量,指定要运行的任务名称,支持单个或多个任务(逗号分隔)。

示例1:仅运行test-job1

{
  "variables": {
    "RUN_JOBS": "test-job1",
    "arg1": "value1",
    "arg2": "value2",
    "arg3": "value3"
  }
}

示例2:同时运行test-job1和test-job2

{
  "variables": {
    "RUN_JOBS": "test-job1,test-job2",
    "arg1": "value1",
    "arg2": "value2",
    "arg3": "value3"
  }
}

3. 执行curl命令触发流水线

保持原curl命令不变,执行后流水线会根据variables.json中的RUN_JOBS值,仅运行指定任务:

curl --request POST "https://gitlab.example.com/api/v4/projects/1412/pipeline" \
     --header "Content-Type: application/json" \
     --header "PRIVATE-TOKEN: <your_access_token>" \
     --data @variables.json

可选调整:默认运行所有任务

若需要在未传递RUN_JOBS时默认运行所有任务,可将每个任务的rules修改为:

rules:
  - if: '$RUN_JOBS != null && $RUN_JOBS !~ /任务名/'
    when: never
  - when: always

此配置下,指定RUN_JOBS时仅运行匹配任务,未指定时运行所有任务。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 00:22:49