Jenkins slackSend: channel alert notifications for #here or specific user - jenkins

Jenkins slackSend question: How to perform an alert notification to a channel that has received a message that needs to be addressed by either any member #here or a specific person ex #Jane.Doe?
Reviewed Jenkins Slack notifications: https://www.jenkins.io/doc/pipeline/steps/slack/
Tried adding #here to the beginning of slackSend message:
failure {
script {
slackSend(
color: "#FF0000",
channel: "${SLACK_CHANNEL}",
message: "#home FAILED"
)
}
}
However, adding #here to slackSend message does not initiate alert notification for that channel.
Suggestions?
Note: Received a comment from a coworker, I am investigating this path:
thought I remember needing to do a look up on users to get an ID and then some special syntax it parses into a username. been a while though.

First you must find the ID of the user and then mention it in the the message, like this example:
def userId = slackUserIdFromEmail('spengler#ghostbusters.example.com')
slackSend(color: "good", message: "<#$userId> Message from Jenkins Pipeline")
Reference: https://plugins.jenkins.io/slack/
Edit:
If you want a put a special or a group mention, you only need follow the format guideline what can you see here : https://api.slack.com/reference/surfaces/formatting#special-mentions

Try it
def emailWithoutDomain = env.BUILD_USER_EMAIL.replaceAll("#.*","").trim()
slackSend ( message: 'I want to mention <#${emailWithoutDomain}> this #user as part of message', teamDomain: '', token: '', channel: '' )

Related

How to use credentials with slackSend

So I'm trying to use slackSend in my Jenkinsfile to post build status on a channel and I'm trying to explicitly define everything like this- (for some reason I have to define it like this)
WithCredentials([string(credentialsId: 'theSlackToken', variable: 'slackCredentials')]) {
slackSend (channel: '#johnsmith', message: 'hello there', color: '#3eb991', failOnError: true, teamDomain: 'myteamsubdomain', token: slackCredentials)
}
But when I use these above lines in my Jenkinsfile I get error saying no such DSL method string.
Please help I will highly appreciate any suggestions.
There's a few issues here:
First for your command to work, you shouldn't use 'withCredentials', only thing you need is the credentialsId, and then set it as tokenCredentialId, like this:
slackSend (channel: '#johnsmith', message: 'hello there', color: '#3eb991', tokenCredentialId: theSlackToken)
Importent: The credentials should be Secret Text!!!
There is no need to use tokenCredentialId in every slackSend command, you can set it as the general slack token for this Jenkins. over Jenkins -> manage Jenkins -> Configure System, then look for Slack, and enter the right credentials for the token you want to be used. Then you can use:
slackSend (channel: '#johnsmith', message: 'hello there', color: '#3eb991'
Using tokenCredentialId in the slack command allows to overwrite the current global token, and like that you can switch between slack apps inside Jenkins.
For more info:
https://plugins.jenkins.io/slack/

Timestamping a slack notification from Jenkins pipeline

def trial = 'jobName'
slackSend color: "good", message: "${trial} build successful"
The above code gives me the below Slack message-
jobName build successful
How do I timestamp the message so that I get the below message-
jobName build successful on dd/mm/yyyy
Thanks for the help.
You could use the below piece of code-
def trial = 'jobName'
def date = new Date().format('dd/MM/yyyy')
slackSend color: "good", message: "${trial} build successful on " + date

Send Slack notification from Jenkins into private channel of other users

What i did:
I managed to send Notifications with Status of every Build to my private Slack Channel. So i configured my Jenkins as well as my Slack app.
What i want to do:
Sending messages to other users private Channels.
What i have tried:
I added channels to my Jenkinsfile and checked them in the Slack App of Jenkins and it wasn't successful. I think i have to create sth like a Bot, which is in the specific Channel i want to send a message to. Very sure that Jenkins can't see the channel because its a private channel of another person(obviously) and is not able to find it. Couldn't find a solution for this Problem.
Thanks a lot for your help, i think i wasted way to much time trying to find an answer for that.
I setup our build pipeline to send Slack notifications to commit authors. The biggest challenge is mapping to the Slack username. I had every developer on the team change their git user.name to match their Slack Display name. This is the most straight-forward way I know to make this work.
git config --global user.name "Mona Lisa" where "Mona Lisa" is the Slack display name of the user.
In the Jenkins pipeline, I used env.GIT_COMMIT_AUTHOR to get this value back.
Note, that the environment variable provides the commit author at the HEAD of whatever was checked out. For pull requests in a multi-branch pipeline, if the PR is not a fast forward, the commit is what the merge would produce, resulting in an author of 'Jenkins'. So, in that case, you would need the author from HEAD~1
In my experience sending Slack messages to a private channel requires OAuth. I have only succeeded sending to private channels via slackSend() when Jenkins is added to Slack as a bot and invited to the channel.
Here's an example pipeline that works:
#!/usr/bin/env groovy
pipeline {
agent {
node {
label "master"
}
}
stages {
stage('Send Notification') {
steps {
script {
def color = "${params.MESSAGE_STATUS}" == "GOOD"? "good" : "warning"
slackSend(color: "${color}", message: "${params.MESSAGE}", channel: "${params.CHANNEL}")
}
}
}
}
parameters {
string(name: 'MESSAGE', defaultValue: 'Hello')
string(name: 'CHANNEL', defaultValue: '#test_private')
choice(name: 'MESSAGE_STATUS', choices: ['GOOD', 'WARNING'], description: '')
}
}
Sending via bots etc. hasn't been successful as Slack reports the channel as non-existant.

Office365ConnectorSend pipeline step does not work

I'm trying to configure Jenkinks notifications to MS Teams. I followed the instructions by setting up and configuring Jenkins app on the relevant channel and Office365 plugin in Jenkins. I get standard job status notifications if I request them.
Now I need to be able to send custom notifications from the pipeline. I was expecting that using office365ConnectorSend pipeline step would do just that:
office365ConnectorSend message:'Test message', webhoolUrl:'office365ConnectorSend message: 'Manual test', webhookUrl: 'https://outlook.office.com/webhook/.../JenkinsCI/...'
When the pipeline runs, everything is reported as working correctly and the job completes successfully, yet the message never appears in teams.
How can post a message?
office365ConnectorSend message:'Test message', webhoolUrl:'office365ConnectorSend message: 'Manual test', webhookUrl: 'https://outlook.office.com/webhook/.../JenkinsCI/...'
Did you check the spelling? it should be webhookUrl not webhoolUrl and only once.
I use something like this in the post pipeline action step, where MSTEAMS_HOOK is defined as an environment variable within the environment {} pipeline directive to the Teams URL.
success {
office365ConnectorSend (
status: "Pipeline Status",
webhookUrl: "${MSTEAMS_HOOK}",
color: '00ff00',
message: "Test Successful: ${JOB_NAME} - ${BUILD_DISPLAY_NAME}<br>Pipeline duration: ${currentBuild.durationString}"
)
}
Try to replace the single quote to double in the webhookUrl.
webhookUrl:"$msteams_url"
Except for the spell error, the script you have been trying works fine. The problem might be with your network restriction. The HTTP request triggered by jenkins might have been blocked. Try pasting the webhook URL in the browser of the system you are using and check the response. If the response says something other than 'Invalid webhook request - GET not supported'. There is a possibility the request has been a failure.
pipeline {
agent any
stages {
stage('Hello') {
steps {
echo 'Hello World'
office365ConnectorSend message: 'Manual test', webhookUrl: 'https://outlook.office.com/webhook/*'
}
}
}
}

Send messages from Jenkins to multiple Slack channels

According to the main Jenkins-Slack documentation you have to configure the Jenkins app for slack and there you specify a single channel where the plugin can post. Now in my case, I need to post to multiple channels and users from a Jenkins server and it is very cumbersome to manage multiple auth tokens. Is there a way to have a single token that would work with all the channels and users? Are there other approaches? I see that the Jenkins plugin has a bot checkbox, but there is almost no documentation on how to make this work.
You can add channel: '#CHANNEL_NAME:
More info: https://jenkins.io/doc/pipeline/steps/slack/
post {
success {
slackSend (channel: '#ch1', color: '#00FF00', message: "SUCCESSFUL: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]' (${env.BUILD_URL})")
}
failure {
slackSend (channel: '#ch1', color: '#FF0000', message: "FAILED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]' (${env.BUILD_URL})")
}
}
I just implemented the solution for my project channels.
There is an Advanced button available in the Post build actions -> Slack notification of a Job.
You can give the base URL and token along with the channel name you want to send the notifications to.
If one has enough permissions to their organization's slack account, one can create an app at https://api.slack.com/apps?new_app=1 which acts as a bot.
Once this bot is installed to workspace [ https://api.slack.com/apps/<org-id>/install-on-team? ] and was given permission to post to targeted channels
( just send a message /invite #<bot-name> in the channel and it will have permissions to post to that channel]. Not sure how to do it for users, though.
Apart from that, slackSend supports sending to multiple channels in a single go.
Multiple channels may be provided as a comma, semicolon, or space delimited string.
https://jenkins.io/doc/pipeline/steps/slack/
For ex., any one of the following are valid:
channel: "#ch-1,#ch-2,#ch-3"
(OR)
channel: "#ch-1;#ch-2;#ch-3"
(OR)
channel: "#ch-1 #ch-2 #ch-3"
Full command may be as:
slackSend (channel: '#ch1 #ch2 #ch3', color: '#00FF00', message: "SUCCESSFUL: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]' (${env.BUILD_URL})")

Resources