snippetMinor
How to test whether a variable exists in the declarative pipeline
Viewed 0 times
declarativethewhetherhowtestexistsvariablepipeline
Problem
I am using the Build User Vars Plugin which sets various variables in the pipeline. Here is what I am currently trying:
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:
Using
In addition to the above, I also tried the following with no luck:
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.BindingUsing
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"Solution
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}"Code Snippets
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}"Context
StackExchange DevOps Q#4225, answer score: 4
Revisions (0)
No revisions yet.