How to Send Slack Notification in Jenkins Pipeline
To send a Slack notification in a Jenkins pipeline, use the
slackSend step provided by the Slack plugin. Configure your Slack workspace and Jenkins integration first, then call slackSend with your message inside the pipeline script.Syntax
The basic syntax to send a Slack notification in a Jenkins pipeline is:
slackSend(channel: '#channel-name', message: 'Your message here')Here’s what each part means:
- slackSend: Jenkins pipeline step to send Slack messages.
- channel: The Slack channel name where the message will be sent (include
#). - message: The text message you want to send.
groovy
slackSend(channel: '#general', message: 'Build completed successfully!')
Example
This example shows a simple Jenkins pipeline that sends a Slack notification when the build finishes successfully.
groovy
pipeline {
agent any
stages {
stage('Build') {
steps {
echo 'Building...'
}
}
}
post {
success {
slackSend(channel: '#general', message: "Build #${env.BUILD_NUMBER} succeeded!")
}
failure {
slackSend(channel: '#general', message: "Build #${env.BUILD_NUMBER} failed.")
}
}
}Output
A message is sent to the #general Slack channel: "Build #123 succeeded!" if the build passes, or "Build #123 failed." if it fails.
Common Pitfalls
Common mistakes when sending Slack notifications in Jenkins pipelines include:
- Not installing or configuring the Slack plugin in Jenkins.
- Using the wrong Slack channel name or missing the
#prefix. - Not setting up the Slack workspace integration and token correctly.
- Trying to send notifications outside the
postblock without proper error handling.
Example of a wrong and right way:
groovy
// Wrong: Missing channel prefix slackSend(channel: 'general', message: 'Build done') // Right: Include # before channel name slackSend(channel: '#general', message: 'Build done')
Quick Reference
Tips for sending Slack notifications in Jenkins pipelines:
- Always install and configure the Jenkins Slack plugin first.
- Use environment variables like
env.BUILD_NUMBERfor dynamic messages. - Send notifications in the
postsection for build status updates. - Use secure credentials for Slack tokens in Jenkins credentials store.
Key Takeaways
Install and configure the Jenkins Slack plugin before using slackSend.
Use slackSend(channel: '#channel', message: 'text') inside pipeline scripts to send messages.
Place slackSend calls in the post block to notify on build success or failure.
Always prefix Slack channel names with # to avoid errors.
Use Jenkins credentials to securely manage Slack tokens.