我希望在创建合并请求时管道中的某些特定作业仅运行一次。例如,为 MR 分配审阅者,或从 QA 环境迁移数据。
Gitlab 有没有办法实现这一点?
你能详细说明一下吗?默认情况下,所有作业仅运行一次。您是在谈论条件运行吗?
如果是这样,我认为
only/except
概念可能会引起兴趣。也许可以使用 only:variables/except:variables
。您必须根据您的用例在后台重新实现一些逻辑,尽管不是那么复杂(设置一个布尔值 true/false)。
请参阅文档了解
only/except
目前(2024 年 7 月)仅使用
rules
/ only
/ 等是不可能的。
您可以使用标签来跟踪哪些 MR 已被“处理”:
向每个新创建的 MR 发布清单的职位实施示例:
stages:
- mr_only_once
- ...
# This job will run only once when a MR is created
checklist:
stage: mr_only_once
rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event'
variables:
MESSAGE: |
## PR checklist
- [ ] I updated the changelog
- [ ] I updated documentation
script:
# Create a bot user and a personal access token; in this case I have put
# this token into GitLab variables and named "BOT_TOKEN"
- TOKEN="$BOT_TOKEN"
# We will be using this GitLab endpoint to interact with the MR;
# the $CI_... variables are provided by GitLab while the job is running
- MERGE_REQUEST_API="$CI_SERVER_URL/api/v4/projects/$CI_PROJECT_ID/merge_requests/$CI_MERGE_REQUEST_IID"
# Get PR labels
- |
LABELS=$(curl -sSf --header "PRIVATE-TOKEN: $TOKEN" "$MERGE_REQUEST_API" | jq -c '.labels')
# Post a comment and assign the ~checklist_done label
- |
if [[ "$LABELS" != *'"~checklist_done"'* ]]; then
# Construct the JSON body with proper escaping
POST_JSON=$(jq -n --arg body "$MESSAGE" --argjson resolved false '{body: $body, resolved: $resolved}')
# Post a comment on the merge request
curl -sSf --request POST \
--header "PRIVATE-TOKEN: $TOKEN" \
--header "Content-Type: application/json" \
--data "$POST_JSON" \
"$MERGE_REQUEST_API/discussions"
# Add a label so that we know not to post the same comment again
curl -sSf --request PUT \
--header "PRIVATE-TOKEN: $TOKEN" \
--header "Content-Type: application/json" \
--data '{"add_labels": "~checklist_done"}' \
"$MERGE_REQUEST_API"
fi