If a build failed in downstream job, how to send email to user who triggered it's upstream job in Jenkins

408 Views Asked by At

Upstream Job:

pipeline {
    agent any

    stages {
        stage('Hello') {
            steps {
                build job: 'test-app', parameters: [string(name: 'dummy', value: "")]
            }
        }
    }
}

Downstream Job:

pipeline {
    agent any

    stages {
        stage('Hello - downstream') {
            steps {
                try{
                sh ''
                }
                catch(e){
                emailext body: "Stage failed, Please check $BUILD_URL", subject: 'Build Failed', recipientProviders: [buildUser()]
            }
        }
    }
}

if downstream job fails, I want to send email to the user who triggered it's upstream job. [buildUser()] is giving errors.

1

There are 1 best solutions below

2
Melkjot On

First, you need to find out which job triggered the downstream job.

def upstreamJob = currentBuild.rawBuild.getCause(hudson.model.Cause$UpstreamCause)

Then it can be found out who triggered the upstream job

def upstreamJobCause = upstreamJob.getUpstreamRun().getCause(hudson.model.Cause$UserIdCause)

From the upstreamJobCause it is possible to retrieve User object and then the email address of that user

def user = User.get(upstreamJobCause.getUserId())
def userMail = user.getProperty(hudson.tasks.Mailer.UserProperty.class).getEmailAddress()
println("User mail: " + userMail)

You can put this code into your catch block. Note that this code will only work for your use case, otherwise error handling is necessary (e.g. if upstream job gets time-triggered the code will not work).

Mailer UserProperty
Model Run
Model User