我有一个 stage1,它创建一个合并请求,然后在合并请求得到 3 个批准者的批准后,我手动触发了 stage2。但是,我想找到一种方法来检查在 stage1 中创建的合并请求批准状态并自动触发 stage2 作业。
1 回答
为了实现这一点,我们将使用 Gitlab API 和jq
包。首先,让我们定义工作。
job_that_creates_mr
是创建合并请求的作业,必须等待 3 个批准者才能触发job_that_triggers_automatically_when_mr_approved
在job_that_creates_mr
中,我假设您使用 gitlab API,特别是https://docs.gitlab.com/ee/api/merge_requests.html#create-mr
POST /projects/:id/merge_requests
为了继续,我们将需要merge request id
,因此请调整您创建 mr 的方式,例如:
MERGE_REQUEST_IID=$(curl -XPOST -s --header "PRIVATE-TOKEN: <access_token>" "https://gitlab.com/api/v4/projects/$CI_PROJECT_ID/merge_requests" --form "source_branch=<source_branch>" --form "target_branch=<target_branch>" --form "title=<mr_title>" | jq '.iid')
通过将结果传递给jq
我们得到merge request id
接下来,我们需要使用我们之前找到number of current approvers
的 mr ,iid
为此我们将使用https://docs.gitlab.com/ee/api/merge_request_approvals.html#merge-request-level-mr-approvals
GET /projects/:id/merge_requests/:merge_request_iid/approvals
一个示例命令是:
NUMBER_OF_APPROVERS=$(curl -s --header "PRIVATE-TOKEN: <access_token>" https://gitlab.com/api/v4/projects/$CI_PROJECT_ID/merge_requests/$MERGE_REQUEST_IID/approvals | jq '.approved_by | length')
现在模板 gitlab-ci.yml 将是:
stages:
- run_after_approval
- create_mr
job_that_triggers_automatically_when_mr_approved:
stage: run_after_approval
script:
- echo 'I run automatically, even though it says manual'
when: manual
job_that_creates_mr:
stage: create_mr
script:
- apk add curl jq
- |
MERGE_REQUEST_IID=$(curl -XPOST -s --header "PRIVATE-TOKEN: <access_token>" "https://gitlab.com/api/v4/projects/$CI_PROJECT_ID/merge_requests" --form "source_branch=<source_branch>" --form "target_branch=<target_branch>" --form "title=<mr_title>" | jq '.iid')
NUMBER_OF_APPROVERS=0
while [[ $NUMBER_OF_APPROVERS -lt 3 ]]
do
NUMBER_OF_APPROVERS=$(curl -s --header "PRIVATE-TOKEN: <access_token" https://gitlab.com/api/v4/projects/$CI_PROJECT_ID/merge_requests/$MERGE_REQUEST_IID/approvals | jq '.approved_by | length')
sleep 60
done
JOB_ID=$(curl -s --header "PRIVATE-TOKEN: <access_token>" "https://gitlab.com/api/v4/projects/$CI_PROJECT_ID/pipelines/$CI_PIPELINE_ID/jobs" | jq '.[] | select(.name=="job_that_triggers_automatically_when_mr_approved") | .id')
curl -XPOST --header "PRIVATE-TOKEN: <access_token" "https://gitlab.com/api/v4/projects/$CI_PROJECT_ID/jobs/$JOB_ID/play"
注意:在这个例子job_that_triggers_automatically_when_mr_approved
中,用你的工作名称更改
这个想法是你已经交换了订单,所以job_that_triggers_automatically_when_mr_approved
它registered first
在管道中,但作为一项manual
工作。
然后创建合并请求的作业等到批准人的数量为3
,然后plays
是job_that_triggers_automatically_when_mr_approved
。