jenkins构建失败后将信息发送到企业微信
Jenkins构建失败后将信息发送到企业微信
在 Jenkins 中,构建失败时可以通过各种方式通知相关人员或系统。其中一种方法是使用 Python 脚本来发送错误消息到企业微信。下面我们将一步步地描述如何实现这一功能。
步骤1: 创建用于发送错误消息的 notice_wrong_model首先,我们需要创建一个名为 `notice_wrong_model` 的脚本,这个脚本负责向企业微信发送错误消息。这个脚本应该包含以下内容:
```python -*- coding: utf-8 -*-
import osimport requestsimport jenkinsdef send_message_to_wechat(jobname, build_number, error_message):
企业微信的 webhook 地址 wechat_webhook = ' 构建信息 message = {
"msgtype": "text",
"text": {
"content": f"构建失败:{jobname},构建编号:{build_number}
错误信息:{error_message}"
}
}
headers = {'Content-Type': 'application/json'}
response = requests.post(wechat_webhook, json=message, headers=headers)
if response.status_code ==200:
print("消息发送成功")
else:
print(f"消息发送失败,状态码:{response.status_code}")
获取构建信息jobname = os.getenv('jobname','')
build_number = os.getenv('BUILD_NUMBER', '')
error_message = os.getenv('ERROR_MESSAGE', '')
if jobname and build_number and error_message:
send_message_to_wechat(jobname, build_number, error_message)
```
步骤2: 添加参数到构建后操作在 Jenkins 中,我们需要将 `notice_wrong_model` 脚本添加到构建后操作中。具体步骤如下:
1. 登录 Jenkins,进入要配置的项目。
2. 点击左侧菜单中的 "构建后操作"。
3. 单击 "+" 按钮,选择 "运行 Python 脚本"。
4. 在 "脚本内容" 中粘贴 `notice_wrong_model` 脚本。
5. 确保脚本中 `YOUR_WEBHOOK_KEY` 的值替换为实际的企业微信 webhook key。
步骤3: 测试测试完成后,构建失败时应该会收到错误消息通知。可以通过检查企业微信的 webhook 日志来确认消息是否发送成功。
注意事项
* 确保 `notice_wrong_model` 脚本中 `YOUR_WEBHOOK_KEY` 的值正确。
* 如果构建失败时没有收到错误消息,请检查 Jenkins 日志和企业微信 webhook 日志以确定问题原因。
* 可以根据需要修改 `notice_wrong_model` 脚本来发送更多的信息或使用其他方式通知相关人员。