Keywords: Jenkins | build number | environment variables
Abstract: This article explores various methods for accessing the current build number in Jenkins continuous integration environments. By analyzing the use of the BUILD_NUMBER environment variable, along with practical examples in command-line and scripts, it systematically introduces technical implementations for integrating build numbers in scenarios such as report generation. The discussion extends to other related environment variables and plugins, providing developers with comprehensive solutions and best practices.
Introduction
In continuous integration (CI) environments, build numbers are key identifiers for tracking software versions and deployment history. Jenkins, as a widely used CI/CD tool, offers multiple mechanisms to access the current build number, which is essential for generating report files with version information, logging, and deployment scripts.
Core Environment Variable: BUILD_NUMBER
Jenkins automatically sets a series of environment variables for each build job, with BUILD_NUMBER being the most direct variable for obtaining the current build number. This variable is an integer that increments with each build, providing a unique sequential identifier for the build process.
In Jenkins job configurations, BUILD_NUMBER can be accessed in the following ways:
- Direct reference in command-line build steps: For example, in a Shell script step, use
echo "Current build number: $BUILD_NUMBER"to output the build number. - Use in custom scripts: In Python, Bash, or other scripting languages, retrieve the value through environment variable interfaces. For instance, in a Python script:
import os; build_number = os.environ.get('BUILD_NUMBER').
Here is a complete example demonstrating how to generate a report file with the build number in a Jenkins job:
#!/bin/bash
# Get the current build number
BUILD_NUM="$BUILD_NUMBER"
# Generate a report file including the build number
REPORT_FILE="report_${BUILD_NUM}.txt"
echo "Build number: ${BUILD_NUM}" > "${REPORT_FILE}"
echo "Report generation completed."This script creates a report file named with the build number during each build, ensuring unique and traceable filenames.
Complete List of Environment Variables and Access Methods
Beyond BUILD_NUMBER, Jenkins provides other useful environment variables, such as JOB_NAME (job name), BUILD_ID (build ID), and WORKSPACE (workspace path). Developers can obtain the full list of these variables through:
- Jenkins official documentation: Refer to the Jenkins environment variables documentation, which details all predefined variables and their descriptions.
- Environment variables page in Jenkins instance: Access
http://<hostname>/jenkins/env-vars.htmlon the Jenkins server (replace<hostname>with the actual hostname), where this page dynamically displays currently available environment variables and their values.
For example, in a Shell script, use the env command to list all environment variables, or output specific variables with echo "$JOB_NAME". This facilitates integrating multiple environmental parameters in complex build workflows.
Extended Applications and Plugin Support
While the BUILD_NUMBER environment variable is the standard solution, additional functionality may be required in advanced scenarios. For instance:
- Custom build number formats: Use Jenkins plugins (e.g.,
Build Name Setter) to modify the display format of build numbers, such as adding timestamps or version prefixes. - Usage in Pipeline scripts: In Jenkins Pipeline, access the build number via
currentBuild.number, offering a more flexible programming interface. Example:echo "Current build number: ${currentBuild.number}". - Integration into reports and notifications: Embed build numbers into test reports, deployment logs, or notification messages (e.g., emails or Slack messages) to enhance traceability. For example, include the build number in the title when generating JUnit reports.
Below is a Pipeline script example illustrating how to combine environment variables with Pipeline syntax:
pipeline {
agent any
stages {
stage('Build') {
steps {
script {
def buildNum = env.BUILD_NUMBER
echo "Starting build number: ${buildNum}"
// Execute build steps
}
}
}
}
}Best Practices and Considerations
In practical applications, it is recommended to follow these best practices:
- Verify environment variable existence: Check if
BUILD_NUMBERis set in scripts to avoid null errors. For example, in Bash:if [ -z "$BUILD_NUMBER" ]; then echo "Error: Build number not found"; exit 1; fi. - Maintain immutability of build numbers: Use build numbers as read-only variables, avoiding modifications within jobs to ensure consistency and audit trails.
- Integrate with version control systems: Associate build numbers with commit hashes from Git or SVN to provide more complete version information. For example, output both build number and commit ID in reports.
- Testing and debugging: Simulate Jenkins environment variables in local or test environments to validate script correctness. Tools like the
env-injectplugin can be used to mock variables.
Additionally, note the scope of environment variables: they are only valid within the context of the build job and do not affect other system processes. For distributed builds, ensure all nodes can correctly access these variables.
Conclusion
Accessing the current build number in Jenkins is a fundamental yet critical task. Through the BUILD_NUMBER environment variable, developers can easily integrate build identifiers into various automation workflows. Combined with official documentation and plugin extensions, this functionality supports a range of applications from simple report generation to complex pipeline management. Adhering to best practices, such as verifying variables and maintaining immutability, can further enhance the reliability and maintainability of build processes. As continuous integration practices evolve, flexibly leveraging these tools will help optimize software delivery pipelines.