You need to enable JavaScript to run this app. 如何在GitLab CI中将提交的变更内容发送到Microsoft Teams
优惠活动
大模型
产品
解决方案
定价
更多

如何在GitLab CI中将提交的变更内容发送到Microsoft Teams

实现方案

你需要先对$changelog变量做特殊字符转义,避免换行、引号等内容破坏POST请求的JSON格式,再将转义后的内容插入到Teams消息卡片的对应字段中即可,修改后的完整配置如下:

Notification:
  before_script: 
    - git show $CI_COMMIT_SHA > /tmp/changes
    # 转义特殊字符:处理反斜杠、双引号、换行,避免JSON格式错误
    - export changelog=$(sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' -e ':a' -e '/^\n*$/{$d;N;ba' -e '}' -e 's/\n/\\n/g' /tmp/changes)
  script:
    - >
      curl --silent --show-error
      --request POST 
      --header 'Content-Type: application/json'
      --url "https://webhook"
      --data '{"@type": "MessageCard","@context": "http://schema.org/extensions","themeColor": "0076D7","summary": "New commit","sections": [{"activityTitle": "New commit","activitySubtitle": "json","activityImage": "https:images","facts": [{"name": "Assigned to","value": "'"$GITLAB_USER_LOGIN"'"},{"name": "Message","value": "'"$CI_COMMIT_MESSAGE"'"},{"name": "Status","value": "'"$CI_JOB_STATUS"'"},{"name": "变更详情","value": "'"$changelog"'"}]}],"potentialAction": [ {"@type": "OpenUri","name": "Link to the page with changes","targets": [{"os": "default","uri": "'"https://git/-/commit/$CI_COMMIT_SHA"'"}]}]}'
  only:
    - master
  tags: 
  - VM_Mobi_Neo
可选优化

如果完整变更内容过长,被Teams卡片长度限制截断,可以将变更内容改为代码块格式渲染,体验更好,只需要在sections配置中新增text字段即可:

# 仅展示修改的sections部分,其余配置不变
"sections": [{
  "activityTitle": "New commit",
  "activitySubtitle": "json",
  "activityImage": "https:images",
  "facts": [
    {"name": "Assigned to","value": "'"$GITLAB_USER_LOGIN"'"},
    {"name": "Message","value": "'"$CI_COMMIT_MESSAGE"'"},
    {"name": "Status","value": "'"$CI_JOB_STATUS"'"}
  ],
  "text": "### 完整变更内容\n```\n'"$changelog"'\n```"
}]

如果还是遇到长度超限问题,可以把git show $CI_COMMIT_SHA改为git show --stat $CI_COMMIT_SHA仅输出变更统计,完整内容引导用户点击卡片自带的GitLab commit链接查看即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 21:45:10