Keywords: Jenkins | BUILD_USER | Timer Trigger | Conditional Plugin | API Script | Automation
Abstract: This article addresses the challenge of retrieving the BUILD_USER variable in Jenkins when jobs are triggered by timers, offering comprehensive solutions that include plugin-based and script-based approaches. It analyzes the root cause, details the core method using Conditional Build Step Plugin, supplements with shell and Groovy scripts, and concludes with implementation steps and best practices to enhance automation flexibility.
Introduction
In Jenkins automation environments, the BUILD_USER environment variable, provided by the Build User Vars Plugin, is commonly used to identify the user who triggered a build, such as in post-job email notifications. However, when a build is triggered by a timer or scheduler, this variable is not automatically initialized, leading to an inability to capture user information correctly. This issue affects many automation scenarios that rely on user identification.
Problem Analysis
Based on the best answer discussion, the BUILD_USER variable is only initialized by the plugin for manual triggers and is missing for timer triggers. This occurs because timer triggers are treated as system actions rather than specific user operations. Therefore, additional mechanisms are needed to simulate or extract user information.
Core Solution: Using Conditional Plugins
The recommended approach is to use the Conditional Build Step Plugin or Run Condition Plugin to resolve this issue. In the job configuration, you can add a conditional step that sets the BUILD_USER_ID variable only when the build is triggered by a timer. For example, use a regular expression to match build causes (e.g., TimerTrigger) to trigger the condition.
Implementation steps: First, install the plugin, then configure the condition in the job's "Build Environment" or "Build Steps." For instance, set a condition such as "when build cause contains 'timer'" and execute a script step to assign BUILD_USER_ID a specific value (e.g., 'system' or extracted from other sources).
Supplementary Methods: Script-Based Solutions
Other answers provide script-based solutions without plugins, suitable for simple or temporary needs.
- Shell Script Method: Query the Jenkins API using curl to retrieve build information. For example:
This script parses the XML response to extract user ID and name, handling cases where timer triggers may return empty values.BUILD_TRIGGER_BY=$(curl -k --silent ${BUILD_URL}/api/xml | tr '<' '\n' | egrep '^userId>|^userName>' | sed 's/.*>//g' | sed -e '1s/$/ \//g' | tr '\n' ' ') echo "BUILD_TRIGGER_BY: ${BUILD_TRIGGER_BY}" - Groovy Script Method: Directly access build causes in a Jenkins Pipeline. For example:
If no user information is available for timer triggers, this method may return null, requiring error handling.def cause = currentBuild.getBuildCauses('hudson.model.Cause$UserIdCause') echo "userName: ${cause.userName}"
Practical Guide and Code Examples
To combine core and supplementary methods, it is advisable to integrate conditional logic in Pipelines. The following example demonstrates a comprehensive approach:
node('master') {
def userInfo = ''
// Check build causes
def causes = currentBuild.getBuildCauses()
causes.each { cause ->
if (cause instanceof hudson.triggers.TimerTrigger) {
userInfo = "Timer Triggered / system"
} else if (cause instanceof hudson.model.Cause$UserIdCause) {
userInfo = "${cause.userName} / ${cause.userId}"
}
}
if (userInfo.isEmpty()) {
// Fallback API call
userInfo = sh(script: "curl -k --silent ${BUILD_URL}/api/json | jq -r '.actions[] | select(.causes) | .causes[] | select(.userId) | \"\(.userName) / \(.userId)\"'", returnStdout: true).trim()
}
env.BUILD_USER = userInfo
echo "BUILD_USER set to: ${env.BUILD_USER}"
}
This code prioritizes build causes and falls back to API queries if needed, ensuring robustness.
Conclusion and Recommendations
Retrieving the BUILD_USER variable for timer-triggered jobs requires a combination of plugin and script strategies. The core solution using conditional plugins offers structured handling, while script-based methods are suitable for rapid prototyping or restricted environments. Recommendations: for complex workflows, use plugins to ensure maintainability; for lightweight scenarios, adopt scripts to reduce dependencies. Regardless of the method, test behavior under different trigger scenarios to avoid unexpected errors in production environments.