How to Make Jenkins Request User Data Available as an Environment Variable

Jenkins jobs serves many purposes. One of the important ones is to use them as self service type of jobs. Usually, you make them available to internal customers. When there are issues, the first thing you want to know may be who requested the job.

I know there is a plugin that makes BUILD_USER_ID available as a environment variable, but I will show you a little trick that doesn’t require another plugin.

First go to Configure section the job you are working on. Click Inject environment variables to the build process under Build Environment section.

Copy and paste the following code in Groovy Script section.

def map = ["REQUEST_USER": currentBuild.getCauses()[0]['userId']]
return map

When you run a build, the REQUEST_USER environment variable is available throughout your build. This is very convenient for logging purposes.  If you check the Environment Variables page for the build the key and the value are there.

Describing it in Job DSL, it looks like the following.

job('foo') {
    environmentVariables {
        groovy('''def map = ["REQUEST_USER": currentBuild.getCauses()[0]['userId']]
return map''')


Leave a Reply

Your email address will not be published.