4

I am using the Build User Vars Plugin which sets various variables in the pipeline. Here is what I am currently trying:

wrap([$class: 'BuildUser']) {
    def safeBuildUser = binding.hasVariable('BUILD_USER') ? BUILD_USER : "unknown"
    echo "${safeBuildUser}"
}

There are times when the plugin does not set the variable. For instance, when the build was launched by an SCM branch scan. When that happens, I receive:

groovy.lang.MissingPropertyException: No such property: BUILD_USER for class: groovy.lang.Binding

Using binding.hasVariable does not appear to work because all of the builds now show "unknown".

In addition to the above, I also tried the following with no luck:

def safeBuildUser = BUILD_USER?: "unknown" 
def safeBuildUser = binding['BUILD_USER']?: "unknown"
def safeBuildUser = binding.variables['BUILD_USER']?: "unknown"
Wes W
  • 41
  • 1
  • 1
  • 3

1 Answers1

4

use try/catch

def safeBuildUser = "unknown"
wrap([$class: 'BuildUser']) {
  try {
     safeBuildUser = BUILD_USER
  } catch (e) {
     echo "User not in scope, probably triggered from another job"
  }
}
echo "Builduser is: ${safeBuildUser}"
Anders Elton
  • 141
  • 2