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/
Related
I'm using the email Extension plugin for Jenkins 2.332.3 but when I get errors with the configuration of the email Extension my build still goes successful even if I get for example
AuthenticationFailedException message: 535 5.7.3 Authentication unsuccessful
Is there a way to get build failure if I have incorrect configurations of emailext?
My stage:
emailext(
attachmentsPattern: "test.txt",
subject: "Test",
body: "Example test",
replyTo: 'test#test.com'
)
When I have configurations valid I get
DEBUG SMTP: message successfully delivered to mail server
I briefly checked the source code of the plugin and this doesn't seem doable. All the errors are caught and handled gracefully. Check here. Also, the execution of the plugin doesn't even return a status code. Check here.
So AFAIU I don't see a way to know whether the email was sent.
Update
After thoroughly checking the code I observed that there is an option to execute a postscript after sending a mail. This script can be specified globally or within the pipeline. So I came up with a very hacky solution with some groovy. Basically, after sending the mail you can capture the response from the SMTP server. This response will have some details you can use to determine whether it's a success or a failure.
On success, you will see a response like the one below.(I used Gmail SMTP server here)
250 2.0.0 OK 1655253667 cc23-20020a05622a411700b00304f98ad3c1sm7772402qtb.29 - gsmtp
On Authentication failure, you should see something like the below.
535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8 https://support.google.com/mail/?p=BadCredentials q18-20020a05622a04d200b002f906fc8530sm8752555qtx.46 - gsmtp
As I mentioned earlier the pipeline simply swallows all the errors that are thrown and from the script, there is no way to access the current build context. Hence as a workaround, I wrote the response to a file and then marked the status of the Job based on this. Please refer to the following pipeline.
pipeline {
agent any
stages {
stage('MailAndFail') {
steps {
script{
echo "Starting Mailing"
def script = "String response = transport.getLastServerResponse();println \"Mail Response: \" + response;File file = new File(\"/var/jenkins_home/workspace/EMAIEXT2222/MailResponse.txt\");file.write response"
emailext(
to: "test#gmail.com",
subject: "Test",
body: "Example test",
replyTo: 'test#test.com',
postsendScript: "$script"
)
sh "cat MailResponse.txt"
def response = readFile(file: 'MailResponse.txt')
if(!response.contains("2.0.0 OK")) {
echo "BUILD FAILURE!!!!"
currentBuild.result = 'FAILURE'
}
}
}
}
}
}
Note: Make sure you change the file write path to a directory in the workspace /var/jenkins_home/workspace/EMAIEXT2222. Also, the print statements in the script will not be shown in the build console. You can see them in the Jenkins log. Also, make sure you approve the groovy script if you get an error that says the script doesn't have permission to execute. You can do this from here: http://JENKINSHOST/scriptApproval/
I use the Jenkins Office 365 Connector and it sends messages of the build status to MS Teams as expected.
Now I want to add the value of a Jenkins job parameter to the message.
My usecase: I use a single job to deploy several services. I want to know in the message which service was deployed.
Notification from Dev_Deploy
Latest status of build #43
Status
Build Success
Remarks
Started by user XXX
Service
service-abc
I've seen in the Advanced configuration that there are Macros and Fact Definitions. Unfortunately there is no documentation in the plugin docs. Perhaps this configuration could help?
There is no option to customize the message in the jenkins GUI.
But a custom message can be specified in the pipeline script:
steps {
// some instructions here
office365ConnectorSend webhookUrl: 'https://outlook.office.com/webhook/123456...',
message: 'Application has been [deployed](https://uat.green.biz)',
status: 'Success',
color: '#0000FF'
}
Hint: The status color is not automatically set. So you have to set the color depending on the status.
Official documentation
In order to get the repository data, you can follow instructions to create a checkout snippet through the Jenkins UI in the configuration.
Once you input the correct URL, browser, and so on, you may invoke the office365ConnectorSend plugin. You may adapt the card sent by passing the factDefinitions attribute an array of [name,template] objects as outlined in Jenkins Docs. You can find an example in the open-source code readme.
there are some defaulted add-ons, but this should set you on the correct path.
Here is an example of my office365ConnectorSend:
office365ConnectorSend (
webhookUrl: "${webhookURL}",
color: "${currentBuild.currentResult} == 'SUCCESS' ? '00ff00' : 'ff0000'",
factDefinitions:[
[ name: "Commit Message", template: "${commit_message}"],
[ name: "Pipeline Duration", template: "${currentBuild.durationString.minus(' and counting')}"]
]
)
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/*'
}
}
}
}
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})")
I can find tons of information in the internet about integrating HipChat in a scripted Jenkins pipeline. So that works fine for me. But how can I post a status message to HipChat that contains an element to trigger an action back in Jenkins?
Currently I have input steps in Jenkins to approve a deployment to the next stage, e.g. PROD.
I also send a HipChat message if approval is needed which contains a link to JENKINS. That looks like this:
hipchatSend color: "${color}", notify: true, room: "Jenkins Team FooBar", message: "${env.JOB_NAME}#${env.BUILD_NUMBER}: ${message}", textFormat: true
/************** PROD **************/
stage ('Approval for PROD') {
try {
timeout(time: approvalTime, unit: approvalTimeUnit) {
input 'Do you approve the deployment to PROD?'
}
} catch (Exception ex) {
finishBuild = true
}
}
// Stop build if flag was set
if (finishBuild)
return
How can I define actions in that hipChat message? Is there a way that I can approve the next build step within HipChat?
I have not found a tutorial or documentation on how to define other kinds of hipchat messages with this plugin.
I could send a POST request to JENKINS if the message would contain standard HTML. Any ideas on how to do that?
How would it work with cards?
Thanks in advance.