1. Overview

In the world of continuous integration and continuous delivery (CICD), the Jenkins pipeline has become a powerhouse for automating software development processes.

In this tutorial, we’ll look at how to utilize global variables in a Jenkins pipeline.

2. Understanding Jenkins Pipeline Global Variables

In the Jenkins pipeline, global variables are predefined objects or values accessible throughout the entire pipeline script. They’re handy tools that Jenkins provides out of the box, ready for use whenever needed. These variables contain valuable information:

  • build environment data
  • job parameters
  • various aspects of the Jenkins system

Moreover, global variables play a crucial role in making pipeline scripts more dynamic and adaptable. By leveraging these variables, we can create more flexible and reusable pipeline code.

Furthermore, global variables help maintain consistency across different pipeline scripts and make it easier to update common values across multiple jobs.

3. Commonly Used Global Variables

Now that we understand what global variables are, let’s explore some of the most frequently used ones in Jenkins pipeline scripts. These variables are often the backbone of pipeline development, providing essential information and functionality.

3.1. env Variables

The env object is a goldmine of environment-related information. It contains a wealth of details about the build environment. Let’s see some commonly used env variables:

  • env.BUILD_NUMBER: current build number
  • env.JOB_NAME: name of the current job
  • env.WORKSPACE: path to the current workspace

To illustrate this concept, we can also look at an example of using the env variable:

pipeline {
    agent any
    stages {
        stage('Environment Info') {
            steps {
                echo "Building ${env.JOB_NAME} #${env.BUILD_NUMBER}"
                echo "Workspace: ${env.WORKSPACE}"
            }
        }
    }
}

This short snippet prints basic information about the current build environment.

Thus, understanding and utilizing these environment variables effectively can enhance the flexibility of the Jenkins pipeline.

3.2. currentBuild Variables

Further, the currentBuild object provides information specific to the current build. Particularly, it’s useful for making decisions based on the build’s status or properties. Some key currentBuild variables show time data and results:

  • currentBuild.result: the result of the build (SUCCESS, FAILURE, UNSTABLE, etc.)
  • currentBuild.duration: duration of the build in milliseconds
  • currentBuild.previousBuild: information about the previous build

To demonstrate the use of currentBuild variables, let’s look at an example:

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                // build steps
            }
        }
    }
    post {
        always {
            echo "Build result: ${currentBuild.result}"
            echo "Build duration: ${currentBuild.duration}ms"
        }
    }
}

This short snippet defines a basic build process with feedback.

3.3. params Variables

Additionally, the params object enables access to build parameters defined in the job configuration. This is useful for creating flexible, parameterized builds. For example, if we define a parameter named DEPLOY_ENV, we can access it via params:

pipeline {
    agent any
    parameters {
        choice(name: 'DEPLOY_ENV', choices: ['dev', 'staging', 'prod'], description: 'Deployment environment')
    }
    stages {
        stage('Deploy') {
            steps {
                echo "Deploying to ${params.DEPLOY_ENV} environment"
                // deployment steps
            }
        }
    }
}

By using these global variables, we create more dynamic informative pipeline scripts.

4. Accessing Global Variables

Understanding the correct syntax and usage patterns is crucial for leveraging the full power of global variables.

Also, accessing global variables in the Jenkins pipeline is straightforward, but there are a few syntax rules to keep in mind:

  • for most global variables, we can use dot notation: variable.property
  • we can access environment variables using env.VARIABLE_NAME or ${VARIABLE_NAME}
  • some variables, like currentBuild, have global properties

Let’s examine an example that demonstrates these different syntaxes:

pipeline {
    agent any
    stages {
        stage('Variable Access') {
            steps {
                echo "Job name: ${env.JOB_NAME}"
                echo "Build number: ${BUILD_NUMBER}"
                echo "Build result: ${currentBuild.result}"
            }
        }
    }
}

Knowing about each method and syntax can help adapt to the current context.

5. Examples of Using Global Variables in Pipeline Scripts

After getting to know global variables and how to access them, let’s see some practical implementations of doing so.

5.1. Conditional Execution Based on Branch Name

To begin with, we can execute code conditionally using the name of a branch.

To further clarify this concept, let’s look at an example to demonstrate it:

pipeline {
    agent any
    stages {
        stage('Deploy') {
            when {
                expression { env.BRANCH_NAME == 'main' }
            }
            steps {
                echo "Deploying main branch to production"
                // deployment steps
            }
        }
    }
}

In the short snippet above, we use the BRANCH_NAME environment variable to conditionally execute the deployment stage only for the main branch.

5.2. Using Build Parameters

Next, let’s look at an example of using a build parameter in a pipeline script:

pipeline {
    agent any
    parameters {
        string(name: 'VERSION', defaultValue: '1.0.0', description: 'Version to deploy')
    }
    stages {
        stage('Deploy') {
            steps {
                echo "Deploying version ${params.VERSION}"
                // deployment steps
            }
        }
    }
}

Here, we define a build parameter VERSION and use it in the pipeline script. This enables us to specify different versions when triggering the build.

5.3. Handling Build Faliures

In addition, we can send a notification when the build fails.

Let’s look at an example to demonstrate this:

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                // build steps
            }
        }
    }
    post {
        failure {
            mail to: '[email protected]',
                 subject: "Failed Pipeline: ${currentBuild.fullDisplayName}",
                 body: "Something is wrong with ${env.BUILD_URL}"
        }
    }
}

In this snippet, we use the currentBuild.fullDisplayName and env.BUILD_URL variables to send a detailed email notification when a build fails.

6. Creating Custom Global Variables

While Jenkins provides many built-in global variables, there are times when we need to define custom variables to suit specific needs. In addition to built-in variables, creating custom global variables enables us to extend Jenkins’ functionality and tailor it to unique project requirements.

6.1. Defining Global Variables in Jenkins Configuration

One way to create custom global variables is through the Jenkins system configuration. This method is particularly useful for variables that need to be available across multiple pipelines.

To define a custom global variable:

  1. Go to Dashboard
  2. Navigate to Manage Jenkins and select Configure System
  3. Check the box Environment variables
  4. Click Add, and enter the name and value of a custom variable

For example, let’s add a variable COMPANY_NAME with the value TechCorp.

Once defined, we can use this variable in any pipeline script:

pipeline {
    agent any
    stages {
        stage('Welcome') {
            steps {
                echo "Welcome to ${env.COMPANY_NAME}'s Jenkins Pipeline!"
            }
        }
    }
}

Thus, we used env.COMPANY_NAME to display a welcome message.

6.2. Using Groovy Script for Custom Global Variables

For more complex scenarios, we can use Groovy scripts to define custom global variables. This approach offers greater flexibility and enables us to create dynamic variables based on logic or external factors.

To use this method, we perform two steps:

  1. Create a Groovy script file (e.g. vars/myCustomVar.groovy) in the Jenkins home directory
  2. Define a function that returns the desired value

To illustrate this approach, here’s an example of a custom variable that generates a timestamp:

// Filename: vars/getTimestamp.groovy
def call() {
    return new Date().format("yyyyMMdd_HHmmss")
}

Now, we can use this custom variable in pipeline scripts:

pipeline {
    agent any
    stages {
        stage('Timestamp') {
            steps {
                script {
                    def timestamp = getTimestamp()
                    echo "Current timestamp: ${timestamp}"
                }
            }
        }
    }
}

We can even create more complex custom variables. For instance, here’s a custom variable that fetches the latest Git tag:

// Filename: vars/getLatestTag.groovy
def call() {
    return sh(script: 'git describe --tags --abbrev=0', returnStdout: true).trim()
}

Furthermore, let’s look at an approach to use this in a pipeline:

pipeline {
    agent any
    stages {
        stage('Deploy') {
            steps {
                script {
                    def latestTag = getLatestTag()
                    echo "Deploying version: ${latestTag}"
                    // deployment steps
                }
            }
        }
    }
}

Finally, by creating custom global variables, we extend the capabilities of Jenkins to better suit the project needs. Whether it’s through system configuration or Groovy scripts, these custom variables enable us to create more powerful, flexible, and project-specific pipeline scripts.

7. Conclusion

In this article, we talked about global variables in the Jenkins pipeline. Specifically, we saw their uses, functions, and practical applications.

In summary, by leveraging global variables we can create more robust and intelligent pipelines that are more easily customizable.