Jenkins Mailer - Send e-mail to user who started build job - jenkins

When a build job fails, I want to send an email to the user who started the job.
I use a jenkins buildfile (Pipeline script). The current code is:
post {
success {
doSomething()
}
failure {
step([$class: 'Mailer', notifyEveryUnstableBuild: true, recipients: 'me#foo', sendToIndividuals: true])
}
changed {
step([$class: 'Mailer', notifyEveryUnstableBuild: true, recipients: 'me#foo', sendToIndividuals: true])
}
}
Sending the mail to me#foo "statically" (i.e. putting the address as in the code above) works well. So the Mailer plugin works well, but I cannot figure out how to make a reference to the user that started the job.
I tried out putting s.th. like the following at the recipients list, but it does not work: '${BUILD_USER_EMAIL}', $BUILD_USER_EMAIL
Thank you in advance for any hint to solve this.

We identified the problem by ourselves: the plugin build user vars was not activated correctly. Now it works.
We use the following code:
pipeline {
...
post {
failure {
step([$class: 'Mailer', notifyEveryUnstableBuild: true, recipients: "${BUILD_USER_EMAIL}", sendToIndividuals: true])
}
changed {
step([$class: 'Mailer', notifyEveryUnstableBuild: true, recipients: "${BUILD_USER_EMAIL}", sendToIndividuals: true])
}
}
}
Thank you for your replies.

Related

How to send the contents of Jenkins workspace as email attachment following the run

How can the contents of Jenkins build workspace be sent as an email attachment, following a test run?. Below is my declarative pipeline code snippet. I can see the folders and files in the workspace following pipeline run, but it doesn't attach except the build log:-
stage('Send Test Report') {
steps {
script {
def testEmailGroup = "saba#abc.com"
// Test teams email
emailext(
subject: "STARTED: jOB '${env.JOB_NAME} [${env.BUILD_NUMBER}]' RESULT: ${currentBuild.currentResult}",
attachLog: true, attachmentsPattern: "**/${WORKSPACE}/*.zip",compressLog: true,
body: "Check console output at ${env.BUILD_URL}" ,
to: testEmailGroup)
}
}
}
You first need to drop workspace contents into a file, here is a snippet similar of what we have on our Jenkins:
stages {
stage('CreateAndSendReport') {
steps {
sh 'echo "Contents" > contents.txt'
}
}
}
post {
always {
archiveArtifacts artifacts: 'contents.txt', onlyIfSuccessful: true
emailext attachLog: true, attachmentsPattern: 'contents.txt',
body: "${currentBuild.currentResult}: Job ${env.JOB_NAME} build ${env.BUILD_NUMBER}\n Link: ${env.BUILD_URL}",
recipientProviders: [developers(), requestor()],
subject: "Jenkins Build Report ${currentBuild.currentResult}: Job ${env.JOB_NAME}"
}
}

Jenkins won't run my build script from perforce

I have a build script I created which is located in a perforce streams depot at //HVS/Main/BuildScripts/hvs_client.jenkinsfile. However, when I run it it's just automatically successful. You can see in the image what it's doing.
I have set the Script Path to the correct location:
And I also have it setup with the correct stream path:
This exact setup works just fine on my windows server running jenkins. The only difference is that I'm trying to migrate my jenkins setup off of a physical machine and onto the cloud. The new master which is running on Ubuntu 20.04 is what is having these issues. I also have one "Node" which is a windows server which has the java agent installed and connected.
This is what my pipeline script looks like:
def channelId = 'removed_for_stackoverflow'
def threadId
def slackResponse
pipeline {
agent {label 'Windows'}
parameters {
choice(name: "BuildType", choices: ['Development', 'Shipping', 'Testing'], description: "What environment are you building to? Default is Development.")
string(name: "SevenZIPDir", defaultValue: "C:\\Program Files\\7-Zip\\7z.exe", description: "Location of 7zip executable.")
booleanParam(name: "clean", description: "Should jenkins clean the workspace?", defaultValue: false)
}
options {
skipDefaultCheckout()
}
stages {
stage('P4 Sync') {
steps {
script {
if (params.clean)
{
cleanWs()
}
p4sync charset: 'none', credential: '5feaca76-6a4a-4540-8a1e-e86ac8b3dc5b', populate: syncOnly(force: false, have: true, modtime: false, parallel: [enable: false, minbytes: '1024', minfiles: '1', threads: '4'], pin: '', quiet: true, revert: false), source: streamSource('//HVS/Main')
}
}
}
// https://github.com/jenkinsci/slack-plugin#bot-user-mode
// https://docs.unrealengine.com/4.27/en-US/ProgrammingAndScripting/ProgrammingWithCPP/UnrealArchitecture/VersioningAssetsAndPackages/
// https://www.perforce.com/manuals/jenkins/Content/P4Jenkins/variable-expansion.html
stage('Notify Slack users') {
steps {
script {
slackResponse = slackSend(channel: channelId, replyBroadcast: true, message: "Beginning build of ${env.JOB_NAME} for CL#${P4_CHANGELIST} ${env.BUILD_URL}")
threadId = slackResponse.threadId
slackResponse.addReaction("stopwatch")
}
}
}
stage('Build Client') {
steps {
retry(3) {
bat("%WORKSPACE%/Engine/Build/BatchFiles/RunUAT.bat BuildCookRun -project=\"%WORKSPACE%/HVS/HVS.uproject\" -noP4 -platform=Win64 -clientconfig=Development -cook -allmaps -clean -build -stage -pak -CrashReporter -archive -archivedirectory=\"%WORKSPACE%/temp/Development/x64\"")
}
}
}
/*stage('Deploy to Steam') {
}*/
stage('Archive Artifacts'){
steps {
dir("temp/${params.BuildType}/x64/WindowsNoEditor") {
bat "\"${params.SevenZIPDir}\" a -mx=1 -mmt=on %WORKSPACE%/temp/HVS_${params.BuildType}_x64_${P4_CHANGELIST}.7z *"
}
archiveArtifacts artifacts: "temp/*.7z", followSymlinks: false, onlyIfSuccessful: true
}
}
}
post {
success {
script {
slackSend(channel: threadId, replyBroadcast: true, message: "Build of ${env.JOB_NAME} for CL#${P4_CHANGELIST} successful! ${env.BUILD_URL}")
slackResponse.addReaction("white_check_mark")
}
}
failure {
script {
slackSend(channel: threadId, replyBroadcast: true, message: "Build of ${env.JOB_NAME} for CL#${P4_CHANGELIST} failed! ${env.BUILD_URL}")
slackResponse.addReaction("red_circle")
}
}
unstable {
script {
slackSend(channel: threadId, replyBroadcast: true, message: "Build of ${env.JOB_NAME} for CL#${P4_CHANGELIST} is not stable #channel ${env.BUILD_URL}")
slackResponse.addReaction("warning")
}
}
}
}
Has anyone seen this before? My one "Node" also has the label "Windows"
I didn't have the Pipeline plugin installd for some reason. It works now.

Reference part of the parameter in Jenkins plugin "publish over cifs"

ALL
Below is my jenkinsfile. I defined a parameter "SVN_TAG" for listing SVN tags. The format of SVN tag is "VERSION-Digit.Digit.Digit". Now I can only only reference the whole parameter in the cifsPublisher "RemoteDirectory" settings. But I want only reference the digit part of the parameter(like "2.2.2"), how should I do this? thanks.
// Jenkins Declarative Pipeline
def PRODUCT_VERSION
pipeline {
agent { label 'Windows Server 16 Node' }
options {
buildDiscarder(logRotator(numToKeepStr: '10', artifactNumToKeepStr: '10'))
}
environment {
TAG = '${SVN_TAG.substring(SVN_TAG.indexOf(\'-\')+1)}'
}
stages {
stage('Initialize') {
steps {
script {
PRODUCT_VERSION = "3.2.0.1"
}
}
}
stage('Setup parameters') {
steps {
script {
properties([
parameters([
[ $class: 'ListSubversionTagsParameterDefinition',
credentialsId: 'xxxxxxxxxxx',
defaultValue: 'trunk', maxTags: '',
name: 'SVN_TAG',
reverseByDate: false,
reverseByName: true,
tagsDir: 'https://svn-pro.xxxx.net:xxxxxx',
tagsFilter: ''
],
])
])
}
}
}
stage('Build') {
steps {
cleanWs()
checkoutSource()
buildSource()
buildInstaller()
}
}
stage('Deploy') {
steps {
copyArtifacts()
}
}
}
}
def copyArtifacts() {
cifsPublisher(publishers: [[configName: 'Server', transfers: [[cleanRemote: false, excludes: '', flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: 'builds\\$JOB_BASE_NAME\\${SVN_TAG}', remoteDirectorySDF: false, removePrefix: '\\unsigned', sourceFiles: '\\unsigned\\*.exe']], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: true]])
}
Your environment variable idea is the correct way, just use double quotes ("") instead of single ones ('') to allow string interpolation, is it only works on double quotes in groovy. You can read more in the Groovy String Documentation.
So just use something like TAG = "${SVN_TAG.split('-')[1]}".
Then use that tag wherever you need it, you can pass it to relevant functions like copyArtifact or just use it as is: "builds\\$JOB_BASE_NAME\\${TAG}".

Is it possible to use promoted builds in Jenkins pipeline and trigger a pipeline job after approving through email

i wanted to send an email to developers to do manual testing and a link to approve the build and then to do the build in production.Can anyone achieve this using jenkins
You can have a step on your pipeline as per below. They cannot approve it on the email, but you can send the URL of the job build on the email:
stage("Stage with input") {
steps {
def userInput = false
script {
// build your custom email message here
emailext (
subject: "Job: ${env.JOB_NAME} - ${env.BUILD_NUMBER}",
body: """Job ${env.JOB_NAME} [${env.BUILD_URL}]""",
recipientProviders: "someone#somewhere.com"
)
def userInput = input(id: 'Proceed1', message: 'Promote build?', parameters: [[$class: 'BooleanParameterDefinition', defaultValue: true, description: '', name: 'Please confirm you agree with this']])
echo 'userInput: ' + userInput
if(userInput == true) {
// do action
} else {
// not do action
echo "Action was aborted."
}
}
}
}
Check here email ext plugin.
And here the input step.

Is there a way to show the name of failed tests in email body via jenkins

I want to see the names of all failed tests in email body when an email is triggered by jenkins using editable email notification plugin.
I am using TestNg with selenium+java.
You can add allure reports in your tests and send the allure links or file via emial as in code below:
stage('Create properties file for allure') {
steps {
sh '''
export CHATBOT_ENV
touch allure-results/environment.properties
'''
}
}
stage('Allure reports') {
steps {
script {
allure([
includeProperties: true,
jdk: '',
properties: [],
reportBuildPolicy: 'ALWAYS',
results: [[path: 'allure-results/']]
])
}
}
}
}
post
{
always
{
echo 'This will always run'
emailext body: "Build URL: ${BUILD_URL}",
attachmentsPattern: "**/path_to_your_report",
subject: "$currentBuild.currentResult-$JOB_NAME",
to: 'nobody#optum.com'
}
}
}
THe build URL can be used to navigate to allure report.

Resources