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'
}
}
Related
The Allure report is not attaching to the Jenkins email. I am using the Jenkins pipeline script and this is my script however this is the error i get in my email:
Groovy Template file [allure-report.groovy] was not found in $JENKINS_HOME/email-templates.
Also I am not able to find allure-report.groovy in my computer
Here is my Jenkins pipeline, I am not sure how to include the template:
pipeline {
agent {
label {
label ""
customWorkspace "/john/qa-end-to-end"
}
}
tools {nodejs "node"}
stages {
stage('Checkout App') {
steps {
dir("${env.HOME}/app") {
echo "Building.."
sh 'git reset --hard HEAD'
sh 'git clean -f -d'
sh 'git pull'
}
}
}
stage('Starting Tests') {
steps {
echo "Starting End to End Tests"
dir("${env.HOME}/qa-end-to-end/") {
sh './tests.sh'
}
}
}
}
post('Publish Report') {
always {
script {
allure([
includeProperties: false,
jdk: '',
properties: [],
reportBuildPolicy: 'ALWAYS',
results: [[path: '$WORKSPACE/${env.HOME}/app/target/allure-results']]
])
}
}
failure {
emailext(
attachmentsPattern: "$WORKSPACE/${env.HOME}/qa-end-to-end/allure-report/index.html",
body: '''${SCRIPT, template="allure-report.groovy"}''',
subject: "Failure in End to End Tests -> Build Number: ${env.BUILD_NUMBER}",
from: "john#gmail.com",
to: "mike#gmail.com"
)
}
}
}
$JENKINS_HOME/email-templates is used to place email body template, generally when you install Jenkins plugin like email, it which includes some pre-defined templates and those templates will be extracted into $JENKINS_HOME/email-templates after plugin installed.
And when you use send email in job's Post Action, you can choose to use one of template of plugin and Jenkins will try to get the template from folder $JENKINS_HOME/email-templates
If you want to use self template, you need to put it into $JENKINS_HOME/email-templates too.
Using custom scripts (those not packaged with email-ext) requires the cooperation of your Jenkins administrator. The steps are relatively simple:
Create the script/template. The name of the script end in the standard extension for the language (.groovy). The template can be named anything
Have your Jenkins administrator place the script inside $JENKINS_HOME\email-templates.
Use the script token with the template parameter equal to your template filename, or in addition the script parameter equal to the custom script name. For example, if the template filename is foobar.template, the email content would look like this ${SCRIPT, template="foobar.template"}.
More detail
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.
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!
Can I use slackSend command in jenkins flow dsl if i have Jenkins ver. 1.656.
I have enabled Slack Notification Plugin and it works fine in most cases, but i wish to display message when build starts.
You can set up script in the pipeline, should be something like this:
def notify(status) {
slackSend channel: "#jenkins",
color: '#d71f85',
message: "${status}",
tokenCredentialId: 'yourtoken'
}
pipeline{
....
stages{
stage('Buildstart) {
steps {
notify("Build Started")
}
}
....
}
}
I have a Jenkinsfile that is running a shell command and I want to send the output of that sh method as the message: of the slackSend method.
I have the following so far, but the message to the slack channel is empty. I'm not certain how to capture the output in a way that I can reference it in the message section:
node {
checkout scm
stage 'run shell command'
def shell_command = sh "ls -l"
def shell_output = apply_cluster
stage 'notify slack-notification'
slackSend channel: '#slack-notifications', color: 'good', message: shell_output, teamDomain: 'company', token: env.SLACK_TOKEN
}
After a little more research, I discovered a couple of things I did not initially understand: The first is that even with defining a function in a Jenkinsfile, if it's a DSL method like sh, it will still get executed, so the second function I defined isn't necessary. Second, if you want to return stdout, you have to specify that as part of the command. The new code looks like this:
node {
checkout scm
stage 'run shell command'
def shell_command = sh script: "ls -l", returnStdout: true
stage 'notify slack-notification'
slackSend channel: '#slack-notifications', color: 'good', message: shell_command, teamDomain: 'company', token: env.SLACK_TOKEN
}