How to pass build number in jenkins pipeline

In Jenkins pipeline, you can pass the build number using the `BUILD_NUMBER` environment variable. The `BUILD_NUMBER` variable is automatically provided by Jenkins and represents the unique identifier of the current build.

To use the `BUILD_NUMBER` in your Jenkins pipeline, you can access it directly using `${BUILD_NUMBER}` or by referencing it through the `env` object like `env.BUILD_NUMBER`. Here’s an example:

    
pipeline {
  agent any
  stages {
    stage('Example') {
      steps {
        script {
          // Access the build number directly
          def buildNumber = "${BUILD_NUMBER}"
          println "Build number: ${buildNumber}"
          
          // Access the build number through the 'env' object
          buildNumber = env.BUILD_NUMBER
          println "Build number: ${buildNumber}"
        }
      }
    }
  }
}
    
  

In the above example, we have a pipeline with a single stage called “Example”. Inside the stage, we use the `script` step to execute scripted pipeline syntax. Within the script block, we access the build number and store it in the `buildNumber` variable. We then print the build number using `println`.

You can use the build number in various ways within your pipeline, such as appending it to the version number, including it in file names, or passing it as a parameter to other steps or scripts.

Leave a comment