Provides Jenkins notification integration with Slack or Slack compatible applications like RocketChat and Mattermost.
-
Get a Slack account: https://slack.com/
-
Configure the Jenkins integration: https://my.slack.com/services/new/jenkins-ci
-
Install this plugin on your Jenkins server:
- From the Jenkins homepage navigate to
Manage Jenkins
- Navigate to
Manage Plugins
, - Change the tab to
Available
, - Search for
slack
, - Check the box next to install.
- From the Jenkins homepage navigate to
If you want to configure a notification to be sent to Slack for all jobs, you may want to also consider installing an additional plugin called Global Slack Notifier plugin.
slackSend color: "good", message: "Message from Jenkins Pipeline"
Additionally you can pass attachments or blocks (requires bot user) in order to send complex messages, for example:
Attachments:
def attachments = [
[
text: 'I find your lack of faith disturbing!',
fallback: 'Hey, Vader seems to be mad at you.',
color: '#ff0000'
]
]
slackSend(channel: "#general", attachments: attachments)
Blocks (this feature requires a 'bot user' and a custom slack app):
blocks = [
[
"type": "section",
"text": [
"type": "mrkdwn",
"text": "Hello, Assistant to the Regional Manager Dwight! *Michael Scott* wants to know where you'd like to take the Paper Company investors to dinner tonight.\n\n *Please select a restaurant:*"
]
],
[
"type": "divider"
],
[
"type": "section",
"text": [
"type": "mrkdwn",
"text": "*Farmhouse Thai Cuisine*\n:star::star::star::star: 1528 reviews\n They do have some vegan options, like the roti and curry, plus they have a ton of salad stuff and noodles can be ordered without meat!! They have something for everyone here"
],
"accessory": [
"type": "image",
"image_url": "https://s3-media3.fl.yelpcdn.com/bphoto/c7ed05m9lC2EmA3Aruue7A/o.jpg",
"alt_text": "alt text for image"
]
]
]
slackSend(channel: "#general", blocks: blocks)
For more information about slack messages see Slack Messages Api, Slack attachments Api and Block kit
Note: the attachments API is classified as legacy, with blocks as the replacement (but blocks are only supported when using a bot user through a custom slack app).
You can upload files to slack with this plugin:
node {
sh "echo hey > blah.txt"
slackUploadFile filePath: "*.txt", initialComment: "HEY HEY"
}
This feature requires botUser mode.
You can send a message and create a thread on that message using the pipeline step. The step returns an object which you can use to retrieve the thread ID. Send new messages with that thread ID as the target channel to create a thread. All messages of a thread should use the same thread ID.
Example:
def slackResponse = slackSend(channel: "cool-threads", message: "Here is the primary message")
slackSend(channel: slackResponse.threadId, message: "Thread reply #1")
slackSend(channel: slackResponse.threadId, message: "Thread reply #2")
This feature requires botUser mode.
Messages that are posted to a thread can also optionally be broadcasted to the
channel. Set replyBroadcast: true
to do so. For example:
def slackResponse = slackSend(channel: "ci", message: "Started build")
slackSend(channel: slackResponse.threadId, message: "Build still in progress")
slackSend(
channel: slackResponse.threadId,
replyBroadcast: true,
message: "Build failed. Broadcast to channel for better visibility."
)
If you wish to upload a file to a thread, you can do so by specifying the channel, and the timestamp of the thread you want to add the file to, separated by a colon. For example:
def slackResponse = slackSend(channel: "cool-threads", message: "Here is the primary message")
sh "echo hey > blah.txt"
slackUploadFile(channel: "cool-threads:" slackResponse.ts, filePath: "*.txt", initialComment: "A file, inside a thread.")
You can update the content of a previously sent message using the pipeline step.
The step returns an object which you can use to retrieve the timestamp and channelId
NOTE: The slack API requires the channel ID for chat.update
calls.
Example:
def slackResponse = slackSend(channel: "updating-stuff", message: "Here is the primary message")
slackSend(channel: slackResponse.channelId, message: "Update message now", timestamp: slackResponse.ts)
This feature requires botUser mode.
Add an emoji reaction to a previously-sent message like this:
Example:
def slackResponse = slackSend(channel: "emoji-demo", message: "Here is the primary message")
slackResponse.addReaction("thumbsup")
You can remove an emoji reaction to a previously-sent message like this:
Example:
def slackResponse = slackSend(channel: "emoji-demo", message: "Here is the primary message")
slackResponse.addReaction("thumbsup")
// ... do some stuff
slackResponse.removeReaction("thumbsup")
This may only work reliably in channels (as opposed to private messages) due to limitations in the Slack API (See "Post to an IM channel").
This does not currently work in a situation where Jenkins is restarted between sending the initial message and adding the reaction. If this is something you need, please file an issue.
This feature requires botUser mode and the reactions:write
API scope.
You can allow link unfurling if you send the message as text. This only works in a text message, as attachments cannot be unfurled.
Example:
slackSend(channel: "news-update", message: "https://www.nytimes.com", sendAsText: true)
There are two pipeline steps available to help with user id look up.
A user id can be resolved from a user's email address with the slackUserIdFromEmail
step.
Example:
def userId = slackUserIdFromEmail('[email protected]')
slackSend(color: "good", message: "<@$userId> Message from Jenkins Pipeline")
A list of user ids can be resolved against the set of changeset commit authors with the slackUserIdsFromCommitters
step.
Example:
def userIds = slackUserIdsFromCommitters()
def userIdsString = userIds.collect { "<@$it>" }.join(' ')
slackSend(color: "good", message: "$userIdsString Message from Jenkins Pipeline")
This feature requires botUser mode and the users:read
and users:read.email
API scopes.
Warning: This functionality is not supported if you are using the blocks
layout mode
Any hex triplet (i.e. '#AA1100'
) can be used for the color of the message. There are also three builtin color options:
Name | Color |
---|---|
good |
green |
warning |
yellow |
danger |
red |
- Configure it in your Jenkins job (and optionally as global configuration) and add it as a Post-build action.
- Log into the Slack compatible application.
- Create a Webhook (it may need to be enabled in system console) by visiting Integrations.
- You should now have a URL with a token. Something like
https://mydomain.com/hooks/xxxx
wherexxxx
is the integration token andhttps://mydomain.com/hooks/
is theSlack compatible app URL
. - Install this plugin on your Jenkins server.
- Follow the freestyle or pipeline instructions for the slack installation instructions.
Use Jenkins Credentials and a credential ID to configure the Slack integration token. It is a security risk to expose your integration token using the previous Integration Token setting.
Create a new Secret text credential:
Select that credential as the value for the Credential field:
You can send messages to channels or you can notify individual users via their
slackbot. In order to notify an individual user, use the syntax @user_id
in
place of the project channel. Mentioning users by display name may work, but it
is not unique and will not work if it is an ambiguous match.
Use the syntax <@user_id>
in a message to mention users directly. See User Id Look Up for pipeline steps to help with user id look up.
This plugin supports configuration as code Add to your yaml file:
credentials:
system:
domainCredentials:
- credentials:
- string:
scope: GLOBAL
id: slack-token
secret: '${SLACK_TOKEN}'
description: Slack token
unclassified:
slackNotifier:
teamDomain: <your-slack-workspace-name> # i.e. your-company (just the workspace name not the full url)
tokenCredentialId: slack-token
For more details see the configuration as code plugin documentation: https://github.com/jenkinsci/configuration-as-code-plugin#getting-started
There's two ways to authenticate with slack using this plugin.
-
Using the "Jenkins CI" app written by Slack, it's what is known as a 'legacy app' written directly into the slack code base and not maintained anymore.
-
Creating your own custom "Slack app" and installing it to your workspace.
The benefit of using your own custom "Slack app" is that you get to use all of the modern features that Slack has released in the last few years to Slack apps and not to legacy apps.
These include:
- Threading
- File upload
- Custom app emoji per message
- Blocks
The bot user option is not supported if you use the Slack compatible app URL option.
Note: These docs may become outdated as Slack changes their website, if they do become outdated please send a PR here to update the docs.
- Go to https://api.slack.com/apps and click "Create New App".
- Pick an app name, i.e. "Jenkins" and a workspace that you'll be installing it to.
- Click "Create App". This will leave you on the "Basic Information" screen for your new app.
- Scroll down to "Display Information" and fill it out. You can get the Jenkins logo from: https://jenkins.io/artwork/.
- Scroll back up to "Add features and functionality".
- Click "Permissions" to navigate to the "OAuth & Permissions" page.
- Scroll down to "Scopes". Under "Bot Token Scopes"
- Add
chat:write
Scope. - (optional) Add
files:write
Scope if you will be uploading files. - (optional) Add
chat:write.customize
Scope if you will be sending messages with a custom username and/or avatar. - (optional) Add
reactions:write
Scope if you will be adding reactions. - (optional) Add
users:read
andusers:read.email
Scope if you will be looking users up by email.
- Add
- (optional) Click "App Home" in the sidebar
- (optional) Edit the slack display name for the bot.
- Return to the "OAuth & Permissions" page.
- At the top of the page, click "Install App to Workspace". This will generate a "Bot User OAuth Access Token".
- Copy the "Bot User OAuth Access Token".
- On Jenkins: Find the Slack configuration in "Manage Jenkins → Configure System".
- On Jenkins: Click "Add" to create a new "Secret text" Credential with that token.
- On Jenkins: Select the new "Secret text" in the dropdown.
- On Jenkins: Make note of the "Default channel / member id".
- On Jenkins: Tick the "Custom slack app bot user" option.
- Invite the Jenkins bot user into the Slack channel(s) you wish to be notified in.
- On Jenkins: Click test connection. A message will be sent to the default channel / default member.
When testing the connection, you may see errors like:
WARNING j.p.slack.StandardSlackService#publish: Response Code: 404
There's a couple of things to try:
If you've ticked Custom slack app bot user
then try unticking it, that mode is for when you've created a custom app and installed it to your workspace instead of the default Jenkins app made by Slack
If you've entered something into Override url
then try clearing it out, that field is only needed for slack compatible apps like mattermost.
Add a log recorder for the StandardSlackService class this should give you additional details on what's going on.
If you still can't figure it out please raise an issue with as much information as possible about your config and any relevant logs.
Install Maven and JDK.
$ mvn -version | grep -v home
Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T08:41:47-08:00)
Java version: 1.7.0_79, vendor: Oracle Corporation
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.4.0-65-generic", arch: "amd64", family: "unix"
Run unit tests
mvn test
Create an HPI file to install in Jenkins (HPI file will be in
target/slack.hpi
).
mvn clean package