Skip to content

Jenkins - 通知

Jenkins 提供了多种方式来通知团队成员构建结果,这对于在 CI/CD 工作流程中保持感知至关重要。

Jenkins 具有内置的电子邮件通知功能。

步骤 1:配置 SMTP 服务器。转到 Manage Jenkins → System。向下滚动到 ‘Jenkins Location’ 部分,确保 ‘Jenkins URL’ 和 ‘System Admin e-mail address’ 已正确设置。然后,找到 ‘E-mail Notification’ 部分。输入您的 SMTP 服务器详细信息(主机名、端口、所需凭据)并测试配置。

步骤 2:在 Job 中配置收件人。在您的 Job 配置(Pipeline 或 Freestyle)中,添加一个构建后操作。对于 Freestyle Job,选择 ‘E-mail Notification’。对于 Pipeline Job,在 post 块内使用 mail 步骤。指定收件人,并选择是针对失败、不稳定还是成功的构建发送电子邮件。

为了获得更多控制并与现代通信平台集成,强烈推荐使用插件。

‘Email Extension’ 插件 (emailext) 相比基本电子邮件通知提供了显著改进。它支持可定制的电子邮件模板(HTML、纯文本)、细粒度触发器(例如,仅在首次失败时发送电子邮件)、可配置的收件人列表(提交变更的开发者、特定用户/组),以及将构建日志或制品添加到电子邮件。在 Manage Jenkins → System 中配置其全局设置,并使用其特定的构建后操作(Freestyle)或 emailext 步骤(Pipeline)。

有适用于流行团队聊天应用的插件:

  • Slack: ‘Slack Notification’ 插件允许向 Slack 频道或用户发送详细的构建状态消息。在 Manage Jenkins → System 中配置它,并在您的 Pipeline 中使用 slackSend 步骤。
  • Microsoft Teams: 类似地,‘Microsoft Teams Connector’ 插件可通过 Webhook 向 Teams 频道发送通知。在 Teams 中配置连接器,在 Jenkins 中添加 Webhook URL (Manage Jenkins -> System),并在 Pipeline 中使用 microsoftTeamsSend 步骤。

对于自定义集成,可以使用诸如 ‘HTTP Request’ 的插件,在构建完成后向任何 Webhook 端点发送带有构建数据(JSON/XML 有效载荷)的 POST 请求。

pipeline {
agent any
stages {
stage('Build') {
steps {
echo 'Building...'
// Your build steps here
}
}
stage('Test') {
steps {
echo 'Testing...'
// Your test steps here
sh 'exit 1' // Simulate failure for example
}
}
}
post {
always {
echo 'This will always run'
// Example: Clean up workspace
}
success {
echo 'Build successful!'
slackSend channel: '#build-status', message: "SUCCESS: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]' (${env.BUILD_URL})"
}
failure {
echo 'Build failed!'
mail to: 'dev-team@example.com',
subject: "FAILURE: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'",
body: "Check console output: ${env.BUILD_URL}"
slackSend channel: '#build-alerts', color: 'danger', message: "FAILURE: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]' (${env.BUILD_URL})"
}
unstable {
echo 'Build unstable (tests failed).'
mail to: 'qa-team@example.com',
subject: "UNSTABLE: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'",
body: "Tests failed. Check results: ${env.BUILD_URL}"
}
}
}

此示例展示了如何在 Declarative Pipeline 中使用 post 部分,根据构建状态发送不同的通知,集成了基本电子邮件和 Slack。