In Jenkins, how do builds know who requested them?

The username isn't put in an easy-to-fetch environment variable, but you can get it using the xml (or json or python) api - as soon as you start a build, http://[jenkins-server]/job/[job-name]/[build-number]/api/xml is populated with details:

<freeStyleBuild>
    <action>
        <cause>
            <shortDescription>Started by user foobar</shortDescription>
            <userName>foobar</userName>
        </cause>
    </action>
    <building>true</building>
    [...]

I tried to use Jenkins Build User Vars plugin and notify a HipChat room that a build was started by a certain user, but BUILD_USER variable was not available to HipChat plugin, possibly because HipChat action happened before Build User Vars plugin injects the variable.

So I installed pre-scm-buildstep plugin and added:

enter image description here]

// Inject environment variables using Groovy

import hudson.model.*

def build = Thread.currentThread().executable
def userCause = build.getCause(hudson.model.Cause$UserIdCause)
def userName = userCause?.userId ?: 'Jenkins'

def envVars = ['BUILD_USER': userName]

for (item in envVars) {
  build.addAction(new ParametersAction([
    new StringParameterValue(item.key, item.value)
  ]))
}

user30997

Please check out Jenkins Build User Vars plugin, it does what you need:

It is used to set following user build variables:

  • BUILD_USER – full name of user started build,
  • BUILD_USER_FIRST_NAME – first name of user started build,
  • BUILD_USER_LAST_NAME – last name of user started build,
  • BUILD_USER_ID – id of user started build.