How to get the BUILD_USER in Jenkins when job triggered by timer?

强颜欢笑 提交于 2019-11-30 11:08:42
Musaffir Lp

This can be done using the Jenkins Build User Vars Plugin which exposes a set of environment variables, including the user who started the build. It gives environment variables like BUILD_USER_ID, EMAIL, etc.

When the build is triggered manually by a logged-in user, that user's userid is available in the BUILD_USER_ID environment variable.

However, this environment variable won't be replaced / initialized when the build is automatically triggered by a Jenkins timer / scheduler.

Attached a screenshot for details

This can be resolved by injecting a condition to the Job by using Conditional Build Step Plugin / Run Condition Plugin,where in to each job we can add a condition to initialize the variable BUILD_USER_ID only when the build is caused or triggered by the Timer or scheduler, by setting a condition using the regular expression..

Build user vars plugin wasn't working for me so I did a quick-and-dirty hack:

BUILD_CAUSE_JSON=$(curl --silent ${BUILD_URL}/api/json | tr "{}" "\n" | grep "Started by")
BUILD_USER_ID=$(echo $BUILD_CAUSE_JSON | tr "," "\n" | grep "userId" | awk -F\" '{print $4}')
BUILD_USER_NAME=$(echo $BUILD_CAUSE_JSON | tr "," "\n" | grep "userName" | awk -F\" '{print $4}')

Install 'Build User Vars Plugin' and use like below:- [ See https://plugins.jenkins.io/build-user-vars-plugin ]

Be sure to check mark the Set jenkins user build variables checkbox under Build Environment for your Jenkins job's configuration.

I'm using a combination of the 'Execute Shell' and 'Env Inject' plugin as follows:

  1. Create an 'Execute Shell' build step that uses shell parameter substitution to write default the value and echo that value into a file. Example highlighted in screen shot below.
  2. Use the 'Env Inject' file to read that file as properties to set.

The token $BUILD_CAUSE from the email-ext plugin is what you are looking for.

You can see the full content token reference when you click the ? just after the Attach build log combobox at the email content configuration.

Some tokens get added by plugins, but this one should be aviable by default.

Edit: As pointed out by bishop in the comments, when using the EnvInject plugin, the $BUILD_CAUSE token gets changed to behave differently.

I wanted to trigger build initiator info to one of my slack/flock group so I used following way to get build initiator email and name by writing in Declarative fashion .

I am just printing here, you can use to store in some environment variable or write in one file giving file path according to your own convenience..

pipeline {
environment {
    BRANCH_NAME = "${env.BRANCH_NAME}"
    }
agent any

stages{
        stage('Build-Initiator-Info'){
                sh 'echo $(git show -s --pretty=%ae)'
                sh 'echo $(git show -s --pretty=%an)'
        }
           }

}

This gets the username who clicked "Build Now" in a Jenkins pipeline job.

@NonCPS
def getBuildUser() {
    return currentBuild.rawBuild.getCause(Cause.UserIdCause).getUserId()
}

Just to elaborate on Musaffir Lp's answer. The Conditional Build Step plugin now supports the Build Cause directly - it requires the Run Condition Plugin also.

If you wanted to detect when the build was started by a timer you can select a Run? value of Build Cause, with Build Cause of: TimerTrigger

This is a little simpler and more robust than using a regex. There are also other triggers you can detect, for example when the build was a result of Source Control Management commit, you can select: SCMTrigger.

I found similar but really working on Jenkins 2.1.x and easy for my understanding way. And it works without any plugins.

if (currentBuild.getBuildCauses('hudson.model.Cause$UserIdCause')['userId']){
    // Will be run only if someone user triggers build
    // Because in other cases this contructions returns null
}

You can use in this construction any classes described here. They will be returns maps with usable values.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!