I am sending slack notification to a channel from Jenkins pipeline, I have installed Jenkins slack plugin https://plugins.jenkins.io/slack and configured Jenkins slack app to send notification to the channel whenever the build fails or succeeds. Instead of sending just a failure message to slack channel I want to notify the user saying that the build failed.
eg: #user error in deploying following project
I referred this steps from jenkins slack plugin
def userIds = slackUserIdsFromCommitters()
def userIdsString = userIds.collect { "<#$it>" }.join(' ')
post {
// Send the build result to slack channel
success {
slackSend (color:'good', message: "<#$userIds>Successfully deployed")
}
failure {
slackSend (color:'danger', message: "<#$userIds>Error in build ${env.JOB_NAME}")
}
}
I am getting null value for $userIds variable.
If it is still relevant for someone, I did so:
........
}
post {
always {
script {
env.GIT_COMMIT_MSG = sh (script: 'git log -1 --pretty=%B ${GIT_COMMIT} | head -n1', returnStdout: true).stripIndent().trim()
env.GIT_AUTHOR = sh (script: 'git log -1 --pretty=%ae ${GIT_COMMIT} | awk -F "#" \'{print $1}\' | grep -Po "[a-z]{1,}" | head -n1', returnStdout: true).trim()
slackSend(
color: color_slack_msg(),
message: """
*${currentBuild.currentResult}:* Job `${env.JOB_NAME}` build `${env.BUILD_DISPLAY_NAME}` by <#${env.GIT_AUTHOR}>
Build commit: ${GIT_COMMIT}
Last commit message: '${env.GIT_COMMIT_MSG}'
More info at: ${env.BUILD_URL}
Time: ${currentBuild.durationString.minus(' and counting')}
""".stripIndent().trim(),
channel: 'slack-channel',
tokenCredentialId: 'SlackToken'
)
}
cleanWs()
}
}
}
def color_slack_msg() {
switch(currentBuild.currentResult) {
case "SUCCESS":
return "good"
break
case "FAILURE":
case "UNSTABLE":
return "danger"
break
default:
return "warning"
break
}
}
this will work if mail = login in slack
This feature is only available for a bot user in slack, not for a Jenkins bot app.
The bot user which you create should have access to read and write message to the channel.
Related
I had set-up notifications via Microsoft Teams for my jenkins job - success, failure, abort, etc.
pipeline {
options {
office365ConnectorWebhooks([[
startNotification: true,
notifySuccess: true,
notifyFailure: true,
notifyAborted: true,
notifyBackToNormal: true,
url: 'webhook_url'
]]
)
} }
With the help of above script i am receiving notifications for all except the failure notifications.
Even i aborted the job i am receiving the notification.
Can anyone help on this issue ?
You can define a notification step regardless of the pipeline completion status using the post section and the always condition like the following:
pipeline {
agent any
stages {
stage('Test notification') {
steps {
echo "Let's simulate a failure"
error('Failing the build.')
}
}
}
post {
always {
echo 'I will always run!'
office365ConnectorSend status: currentBuild.currentResult, webhookUrl: 'webhook_url'
}
}
}
Note that the syntax has changed.
To learn more about the plugin usage:
Office 365 Connector plugin
Office 365 Connector steps
And about the Jenkins post usage:
Jenkins Pipeline Syntax
im trying to post Jenkins job script output to slack notification: but i cant able to access the output in slack notification setting.
other than /env-vars.html/ the variables here i can't able to access any other variable.
At the moment there is no support to get the variables other than env vars in Jenkins. We can use "Environment Injector" plugin but I am not sure about that plugin.
For your case you can create a "Pipeline" with the below scripted pipeline
node('JENKINS_NODE') {
git([url: 'GITHUB_REPO_URL', branch: 'BRANCH'])
def getResult
stage ('Execute Script') {
getResult = sh(
script: "python test.py",
returnStdout: true,
)
}
stage ('Send Slack Notification') {
slackSend channel: '#YOUR_SLACK_CHANNEL', color: 'good', message: getResult'
}
}
I have downloaded & installed Slack Notification Plugin in jenkins and using slackSend in the pipeline, it was working before but now getting an error as below: After this i downloaded Global Slack Notifier plugin, but still the same error,is there any setup required? Please advice
[Pipeline] slackSend
run slackstepsend, step null:false, desc null:false
Slack Send Pipeline step configured values from global config - baseUrl: true, teamDomain: true, token: true, channel: false, color: false
ERROR: Slack notification failed. See Jenkins logs for details.
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: FAILURE
Code is as below:
if (dstry) {
def status = sh(returnStatus: true, script: "set +e; terraform plan -destroy -var-file=my.tfvars -out=destroy.tfplan")
echo "Plan Status : ${status}"
def destroyExitCode = sh(returnStatus: true, script: "set +e; terraform destroy -auto-approve")
echo "Terraform Destroy Exit Code: ${destroyExitCode}"
if (destroyExitCode == "0") {
slackSend channel: '#ci', color: 'good', message: "Destroy Applied ${env.JOB_NAME} - ${env.BUILD_NUMBER} ()"
currentBuild.result = 'SUCCESSFUL'
} else {
slackSend channel: '#ci', color: 'danger', message: "Destroy Failed: ${env.JOB_NAME} - ${env.BUILD_NUMBER} ()"
currentBuild.result = 'FAILURE'
}
}
Did you add the slack Jenkins token for integration?
Go to this Jenkins CI url, search for your team domain, then add a new configuration. Copy the name of the token or the token itself. Then go to your Jenkins pipeline script and add to slackSend, the domain and the token credential ID or the token in plain text (not secured). Should look something like this:
slackSend channel: '#ci', color: 'good', message: "Destroy Applied ${env.JOB_NAME} - ${env.BUILD_NUMBER}", teamDomain: 'your_domain.slack.com', tokenCredentialId: 'your_id'
or if you want to use the token in plain text token:'your_token' instead of the tokenCredentialId
Hope this helps!
How do I grep the Jenkin's output and email the user if the word "Fail" shows up in the output? I want to use Jenkin's pipeline system.
I am running an ssh command using Jenkins. I want at the end of the job to grep the Jenkin's output and send an email to the admin if there are any failures (if the word "Fail" shows up in the output). How can I do that with Pipeline?
You can use the pipeline step httpRequest to send a http request to the build console url: BUILD_URL/consoleText
You can get the current BUILD_URL via global variable: currentBuild.absoluteUrl or env.BUILD_URL
pipeline {
agent any
stages {
stage('test') {
steps {
script {
def response = httpRequest([
// if your jenkins need login,
// add your jenkins account or a common accout
// to jenkins credentials, below authentication value is
// the credential Id
authentication: 'ba2e4f46-56f1-4467-ae97-17b356d7f854',
url: currentBuild.absoluteUrl + 'consoleText'])
if(response.status == 200) {
if(response.content =~ /Fail/) {
sh 'echo Build fail'
// add step to send mail
}
else {
sh 'echo Build successfully'
}
}
else {
echo 'Fail to fetch the build console log'
}
}
}
}
}
}
I have deployed the pipeline-as-code docker demo with multibranch.
It works alright. I added my github username as the organization and when I make a pull request, the tests are run.
However, when some other user makes a pull request, their tests are also run. I would like to manually approve which pull requests from external contributors are good to run in my jenkins server. Is there a way to do that?
I can do it with ghprb, but it is not compatible with pipelines, and I want to migrate my jobs to pipelines.
please try adding these lines in your pipeline script:
node('slaveName') {
properties([
parameters([
string(
defaultValue: 'whitelisted1#gmail.com,whitelisted2#gmail.com',
description: 'comma separated whitelisted emails',
name: 'WHITELIST'
)
])
])
def authorEmail
stage('Git') {
authorEmail = sh([
// git log format docs here: https://git-scm.com/docs/pretty-formats
script : "git log -1 --format='%aE'",
returnStdout: true
]).trim()
boolean allowRun = isWhitelisted(env.WHITELIST, authorEmail)
if (allowRun) {
echo "email ${authorEmail} is whitelisted, proceed execution"
} else {
echo "email ${authorEmail} is not in whitelist ${env.WHITELIST}, proceed jenkins job?"
input message: 'Proceed?'
// or just abort build with non-zero shell exit
// currentBuild.result = 'FAILURE'
// sh "exit 10"
}
}
}
}
#NonCPS
boolean isWhitelisted(whitelist, email) {
def res = whitelist.tokenize(" ,;").find { white -> white == email }
return null != res
}