配置 Gitlab-CI 触发企业微信群机器人发送通知

最近企业微信增加了群机器人功能,可以拿来在 Gitlab-CI 打包完成后发送通知,分享下配置方法:

配置群机器人:

  1. 在相应群右键-添加群机器人-设置相关参数

  2. 可以看到给出了相应的 Webhook 地址和使用文档,本质就是发一个 POST 请求。 url 包含了相关 key , JSON 包含消息内容。
    消息内容支持三种类型,具体语法可以参考文档。

    • text
    • markdown
    • 图文
  3. 然后可以用 Postman 或者 Terminal 来测试能否收到(替换为自己的 WebHook)。

curl 'http://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx' \
   -H 'Content-Type: application/json' \
   -d '
   {
        "msgtype": "text",
        "text": {
            "content": "hello world"
        }
   }'

配置到 Gitlab-CI:

在原来正常的打包流程基础上,写一个打包成功(失败)后触发的脚本,放在和 gitlab-ci.yml 同级,传入不同参数,发送不同数据,我这里通过第一个参数判断成功失败:

  • 成功的参数: on_success branch_name commit_hash apk_name
  • 失败的参数:on_failure
#!/usr/bin/env bash

if [[ $1 == "on_success" ]];
then
curl 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=48d51802-bf41-4641-b0aa-33d67a2c9ed8' \
      -H 'Content-Type: application/json' \
      -d '
      {
        "msgtype": "markdown",
        "markdown": {
          "content": "分支:'$2'   提交:'$3'
          '$4'.apk 打包完成!
          [点击查看](https://your_url/pipelines)"
        }
      }'
elif [[ $1 == "on_failure" ]];
then
curl 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=48d51802-bf41-4641-b0aa-33d67a2c9ed8' \
      -H 'Content-Type: application/json' \
      -d '
      {
        "msgtype": "markdown",
        "markdown": {
          "content": "打包失败!
          [点击查看](https://your_url/pipelines)"
        }
      }'
fi

改一下 gitlab-ci.yml 文件中的配置调用脚本:

...
build_production_release:
  stage: build_production_release
  script:
    - ./gradlew assembleProductionRelease
    - mv app/build/outputs/apk/production/release/*.apk .
    - sh ./Android_Gitlab_Ci_Notification.sh "on_success" ${CI_COMMIT_REF_SLUG} ${CI_COMMIT_SHA:0:8} "PackageName_productionRelease_${CI_COMMIT_REF_SLUG}_${CI_COMMIT_SHA:0:8}"
  artifacts:
    name: "PackageName_productionRelease_${CI_COMMIT_REF_SLUG}_${CI_COMMIT_SHA:0:8}"
    paths:
      - ./*.apk
    expire_in: 2 weeks
  when: manual
    # except:
    # - feature/CI-CD

clean_build_job:
  stage: clean
  script:
    - ./gradlew clean
    - sh ./Android_Gitlab_Ci_Notification.sh "on_failure"
  when: on_failure
  ...
  • 在打包的 job ( build_production_release ) ./gradle assemblexxx 之后传入相关参数调用脚本成功的代码
    sh ./Android_Gitlab_Ci_Notification.sh "on_success" ${CI_COMMIT_REF_SLUG} ${CI_COMMIT_SHA:0:8} "PackageName_productionRelease_${CI_COMMIT_REF_SLUG}_${CI_COMMIT_SHA:0:8}"

  • 打包失败时的 job ( clean_build_job ) 传入 on_failure 调用脚本失败的代码
    sh ./Android_Gitlab_Ci_Notification.sh "on_failure"