Jenkins在Debian上实现通知与报警的方法
邮件是Jenkins通知的基础方式,通过Email Extension Plugin可实现灵活的内容定制与触发条件设置。
Manage Jenkins
→Manage Plugins
→Available
标签,搜索“Email Extension Plugin”并安装。Manage Jenkins
→Configure System
→Extended E-mail Notification
部分,填写SMTP服务器信息(如smtp.example.com
、端口587
)、认证信息(用户名/密码或应用专用密码,如Gmail需开启两步验证并生成专用密码)、默认主题(如[Jenkins]
)及内容类型(推荐text/html
以支持富文本)。Extended E-mail Notification
部分点击Test Configuration
,若收到测试邮件则说明配置成功。Configure
页面→Post-build Actions
→点击Add post-build action
→选择“Editable Email Notification”,设置收件人(如dev-team@example.com
)、邮件主题(可使用Groovy脚本动态生成,如${JOB_NAME} - Build #${BUILD_NUMBER} - ${BUILD_STATUS}
)、正文内容(支持HTML,如包含构建日志链接),并配置触发条件(如“Failure”(失败)、“Success”(成功)、“Unstable”(不稳定)等)。通过集成Slack、企业微信等工具,可将构建状态实时推送至团队沟通频道。
Manage Plugins
→Available
搜索安装)。Settings
→Apps
→Manage
→Build
,创建Jenkins集成并获取Integration Token
。Post-build Actions
中添加“Slack Notifications”,填写Slack频道(如#jenkins-alerts
)、Token及发送条件(如失败时发送)。curl
命令发送消息(如curl 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY' -H 'Content-Type: application/json' -d '{"msgtype": "text", "text": {"content": "Jenkins Job ${JOB_NAME} 构建${BUILD_STATUS}"}}'
)。通过Prometheus+Grafana或Zabbix等工具,可实现Jenkins性能指标的可视化及阈值告警。
Manage Plugins
→Available
搜索安装),配置Jenkins暴露Prometheus指标(默认路径/prometheus
)。prometheus.yml
中配置scrape_configs
)。通过插件监控Jenkins服务器状态,及时发现资源瓶颈或服务异常。
Manage Plugins
→Available
搜索安装),无需额外配置即可监控Jenkins的内存占用、CPU使用率、HTTP响应时间、当前请求数等指标,通过/monitoring
路径访问可视化页面。Manage Plugins
→Available
搜索安装),生成关于Jenkins服务器状态的HTML报告(包含系统负载、磁盘空间、JVM内存等信息),可通过/monitoring
路径查看。通过编写脚本定期检查Jenkins服务状态或构建结果,触发自定义告警(如企业微信、钉钉机器人)。
import requests
import smtplib
from email.mime.text import MIMEText
def check_jenkins_status():
try:
response = requests.get("http://localhost:8080", timeout=5)
if response.status_code != 200:
send_alert("Jenkins服务不可用")
except Exception as e:
send_alert(f"Jenkins监控异常: {str(e)}")
def send_alert(message):
# 配置邮件告警(以SMTP为例)
sender = "jenkins-alert@example.com"
receivers = ["admin@example.com"]
msg = MIMEText(message)
msg['Subject'] = "Jenkins告警"
msg['From'] = sender
msg['To'] = ", ".join(receivers)
try:
smtp = smtplib.SMTP("smtp.example.com", 587)
smtp.starttls()
smtp.login("your-email@example.com", "your-password")
smtp.sendmail(sender, receivers, msg.as_string())
smtp.quit()
except Exception as e:
print(f"邮件发送失败: {str(e)}")
if __name__ == "__main__":
check_jenkins_status()
jenkins_monitor.py
,通过cron
设置定时任务(如每5分钟运行一次):*/5 * * * * /usr/bin/python3 /path/to/jenkins_monitor.py
。