Using Environment Variables and Build Parameters in Jenkins

Environment variables and build parameters are two essential features in Jenkins that allow you to customize build behavior and pass dynamic information across different stages.

Using Environment Variables and Build Parameters in Jenkins

Jenkins is a powerful automation tool for building, testing, and deploying code, and one of its strengths lies in its ability to create flexible, parameterized pipelines. Environment variables and build parameters are two essential features in Jenkins that allow you to customize build behavior and pass dynamic information across different stages.

In this post, we will dive deep into how to leverage environment variables and build parameters to optimize Jenkins pipelines, automate tasks efficiently, and enable dynamic configurations based on various conditions.

1. Introduction to Environment Variables in Jenkins

Environment variables are key-value pairs that provide contextual information to running jobs and pipelines. In Jenkins, environment variables are used to store and retrieve data that can influence job configurations, scripts, or stages of your pipeline.

Environment variables can store a variety of values, such as:

  • Paths to directories and files.
  • Jenkins-specific information (build number, job name, workspace path).
  • Credentials and secrets (such as API keys or passwords).
  • Dynamic data such as branch names or Git commit hashes.

2. Predefined Environment Variables

Jenkins automatically provides a set of predefined environment variables for every job, which gives useful information about the Jenkins build environment and job configuration.

2.1 Common Predefined Environment Variables

Some of the most commonly used predefined environment variables include:

  • BUILD_NUMBER: The unique build number for the current run.
  • BUILD_ID: A unique identifier for the current build.
  • JOB_NAME: The name of the Jenkins job.
  • WORKSPACE: The directory where Jenkins checks out the code for the current build.
  • GIT_COMMIT: The Git commit hash for the current build (if the job involves Git).
  • BRANCH_NAME: The branch name of the SCM being built.
  • NODE_NAME: The name of the node (agent) where the build is running.
  • JENKINS_HOME: The location of the Jenkins installation directory.
  • JENKINS_URL: The URL of the Jenkins server.

These predefined environment variables can be accessed in your build scripts, pipelines, and even job configurations to create dynamic, context-aware workflows.

3. Setting Up Custom Environment Variables

In addition to predefined variables, you can define custom environment variables in Jenkins to pass specific information across builds and jobs.

3.1 Setting Environment Variables in Jenkins Jobs

You can manually define environment variables for a specific job in Jenkins. In case your Job is the Freestyle project, in the Configuration of the Job, you will see the following section:

Jenkins Job - Build Environment Section

Steps to Set Environment Variables in a Jenkins Job:

  1. Go to your Jenkins job’s configuration page.
  2. Scroll down to the Build Environment section.
  3. Check the box Provide Node & Label configuration (or similar based on your version).
  4. Save the changes.

Add key-value pairs for the custom environment variables. For example:

API_KEY = my-api-key-123
BUILD_TYPE = debug

The custom environment variables will now be accessible within the job's build scripts and pipeline stages.

3.2 Using Environment Variables in a Jenkinsfile

In a Jenkins Pipeline (Jenkinsfile), environment variables can be defined in two ways:

Using the withEnv block in Scripted Pipelines:

node {
    withEnv(['API_KEY=my-api-key-123', 'BUILD_TYPE=debug']) {
        stage('Build') {
            echo "API_KEY is ${env.API_KEY}"
            echo "BUILD_TYPE is ${env.BUILD_TYPE}"
        }
    }
}

Using the environment block in Declarative Pipelines:

pipeline {
    agent any
    environment {
        API_KEY = 'my-api-key-123'
        BUILD_TYPE = 'debug'
    }
    stages {
        stage('Build') {
            steps {
                echo "API_KEY is ${env.API_KEY}"
                echo "BUILD_TYPE is ${env.BUILD_TYPE}"
            }
        }
    }
}

In both approaches, environment variables can be used directly inside stages or steps.

4. Introduction to Build Parameters

While environment variables store predefined or fixed data, build parameters allow you to pass dynamic values to Jenkins jobs at runtime. Build parameters are useful when you want to configure a job differently based on user input or external conditions.

5. Configuring Build Parameters in Jenkins

To use build parameters, you need to configure the job to accept parameters and then use those parameters within the pipeline.

5.1 Step-by-Step: Adding Parameters to a Job

  1. Open the configuration page of the Jenkins job.
  2. Scroll down to the General section.
  3. Check the box This project is parameterized.
  4. Click Add Parameter to define the type of parameter you want to create (e.g., String Parameter, Boolean Parameter, Choice Parameter, etc.).
  5. Enter the name and default value (if applicable) for the parameter.
  6. Save the job.

Once the job is parameterized, Jenkins will display input fields when the job is manually triggered, allowing users to input values for those parameters.

5.2 Types of Build Parameters

There are several types of build parameters available in Jenkins:

  • String Parameter: A simple text input that accepts a string value.
  • Boolean Parameter: A checkbox that represents a true/false value.
  • Choice Parameter: A dropdown list of predefined options.
  • File Parameter: Allows users to upload a file that can be used by the build.
  • Password Parameter: Accepts sensitive values like passwords or API keys (masked from the UI).
  • Run Parameter: Selects a specific build from another job.

Each parameter type has its specific use case, allowing you to configure jobs for flexible and dynamic behavior.

6. Using Build Parameters in Jenkins Pipelines

Once build parameters are defined in the job, they can be referenced and used in the pipeline or build scripts.

6.1 Passing Parameters in a Declarative Pipeline

In a Declarative Pipeline, build parameters can be accessed using the ${params} syntax.

pipeline {
    agent any
    parameters {
        string(name: 'BRANCH_NAME', defaultValue: 'main', description: 'Branch to build')
        booleanParam(name: 'RUN_TESTS', defaultValue: true, description: 'Run tests during build?')
    }
    stages {
        stage('Build') {
            steps {
                echo "Building branch: ${params.BRANCH_NAME}"
                if (params.RUN_TESTS) {
                    echo "Running tests..."
                } else {
                    echo "Skipping tests."
                }
            }
        }
    }
}

In this example, the BRANCH_NAME and RUN_TESTS parameters are passed into the pipeline and used in the build steps.

6.2 Passing Parameters in a Scripted Pipeline

In Scripted Pipelines, parameters are accessed similarly, but with a more flexible structure.

node {
    def branch = params.BRANCH_NAME ?: 'main'
    def runTests = params.RUN_TESTS ?: true

    stage('Build') {
        echo "Building branch: ${branch}"
        if (runTests) {
            echo "Running tests..."
        } else {
            echo "Skipping tests."
        }
    }
}

Scripted pipelines allow more dynamic control over the use of parameters, but they require explicit variable declarations.

7. Best Practices for Environment Variables and Build Parameters

To ensure efficient and secure use of environment variables and build parameters, follow these best practices:

  • Avoid Hardcoding Sensitive Data: Avoid hardcoding sensitive information (e.g., API keys, passwords) directly in the Jenkinsfile. Use the Credentials Plugin to securely store and retrieve credentials.
  • Use Descriptive Names: Use clear and descriptive names for both environment variables and parameters to avoid confusion in large, complex jobs.
  • Set Default Values: Always define default values for build parameters to prevent null or invalid values from being used.
  • Document Parameters: Document the purpose of each parameter in the Jenkinsfile or job configuration to help team members understand how they affect the build process.
  • Parameterize Jobs: Use parameters to make jobs flexible and reusable across different environments (e.g., development, testing, production).

Conclusion

In this post, we explored the power of environment variables and build parameters in Jenkins. By understanding how to use both predefined and custom environment variables, as well as how to configure and pass build parameters, you can create dynamic and flexible Jenkins pipelines that adapt to different scenarios and inputs.

Environment variables help manage context-sensitive information, while build parameters allow users to customize jobs at runtime, making Jenkins pipelines more versatile and maintainable.

By following the best practices outlined above, you can ensure that your Jenkins jobs are secure, efficient, and easy to manage.

This concludes the detailed post on Using Environment Variables and Build Parameters in Jenkins, part of the larger topic on Automating Build Processes with Jenkins. Stay tuned for more Jenkins tutorials to further enhance your CI/CD pipelines!

Read next

Integrating Jenkins with a Kubernetes Cluster for CI/CD

Jenkins is one of the most widely used tools for CI/CD. Integrating Jenkins with Kubernetes allows for a more scalable, efficient, and flexible CI/CD environment, enabling organizations to automate the build, test, and deployment processes in a cloud-native way.