如何通过 GitLab API 在 GitLab CI/CD 中运行特定作业?

问题描述 投票:0回答:1

我有一个curl命令(见下文),目前我的管道中有一项作业,当我执行下面的curl命令时,它会运行我的管道并执行我唯一的作业,即

test-job1
。现在我已经添加了
test-job2
。我将在那里有更多的作业,但我希望能够配置作业,以便我可以选择作业(本质上在作业中创建规则),以便我可以通过curl命令运行这些特定作业并且仅运行那些作业.

谁能提供我所有的步骤吗?

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
build-job:
  stage: build
  script:
    - echo "Hello, $GITLAB_USER_LOGIN!"

test-job1:
  stage: test
  script:
    - python3 mydumbscript.py $arg1 $arg2 $arg3
how to run particular jobs in gitlab ci/cd via gitlab api? 
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

deploy-prod:
  stage: deploy
  script:
    - echo "This job deploys something from the $CI_COMMIT_BRANCH branch."
  environment: production
python gitlab gitlab-ci
1个回答
0
投票

正如您已经提到的,您想查看

rules
来控制作业何时运行。这将允许您在同一管道中配置多个作业并在某些情况下执行它们。

以您发布的管道为例(假设作业通常在 git 的

push
操作上运行),您可以使用以下内容过滤它们:

build-job:
  rules:
    - if: $CI_PIPELINE_SOURCE == "push"
  stage: build
  script:
    - echo "Hello, $GITLAB_USER_LOGIN!"

test-job1:
  stage: test
  rules:
    - if: $CI_PIPELINE_SOURCE == "push"
  script:
    - python3 mydumbscript.py $arg1 $arg2 $arg3

test-job2:
  rules:
    - if: $CI_PIPELINE_SOURCE == "api" # Trigger only with API calls
  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

deploy-prod:
  rules:
    - if: $CI_PIPELINE_SOURCE == "push"
  stage: deploy
  script:
    - echo "This job deploys something from the $CI_COMMIT_BRANCH branch."
  environment: production

这只是一个简单的示例,但您可以通过使用所有 CI/CD 预定义变量来添加更多执行条件,甚至显式排除某些情况下的作业,从而获得更复杂的逻辑。

请参阅此 doc 了解

$CI_PIPELINE_SOURCE
可以具有的所有可能值。

© www.soinside.com 2019 - 2024. All rights reserved.