如何通过GitLab API触发并传递参数给GitLab CI/CD中的作业?
我可以通过REST API调用GitLab API来传递参数给一个任务,以触发一个特定的工作吗?我有一个Python脚本,它是这个工作的一部分,我想把参数传递给这个脚本。
我想通过GitLab API来调用这个工作。请求应该是什么样子的呢?
比如,根据文档,触发管道的curl命令看起来是这样的:
curl --request POST \
"https://gitlab.example.com/api/v4/projects/project_id/trigger/pipeline?token=**************&ref=main"
问题是:在我下面的例子中,我有一个叫test-job1的工作,它运行一个Python脚本,叫做mydumbscript.py,我传入了一些参数,比如$arg1……我可以通过GitLab API传递这个参数并触发这个特定的工作吗?
我在GitLab上设置了一个项目,叫做myproject,这里有一个示例的.gitlab-ci.yml文件:
build-job:
stage: build
script:
- echo "Hello, $GITLAB_USER_LOGIN!"
test-job1:
stage: test
script:
- python3 myproject/script/mydumbscript.py $arg1 $arg2 $arg3
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
1 个回答
1
来自GitLab文档的内容:
你可以在触发API调用时传递任意数量的CI/CD变量。这些变量的优先级最高,会覆盖所有同名的变量。
curl --request POST \
--form token=TOKEN \
--form ref=main \
--form variables[UPLOAD_TO_S3]="true" \
"https://gitlab.example.com/api/v4/projects/123456/trigger/pipeline"
在被触发的流水线中,CI/CD变量会显示在每个任务的页面上,但只有拥有“所有者”和“维护者”角色的用户才能查看这些值。
这里的“key”就是你在流水线开始运行时定义的变量。你可以像--form variables那样添加多行。
顺便说一下,这些信息和更多内容可以在这里找到:https://docs.gitlab.com/ee/ci/triggers/#pass-cicd-variables-in-the-api-call