Managing Environment Variables in Jenkins: A Practical Guide

Updated: February 3, 2024 By: Guest Contributor Post a comment

Introduction

Jenkins, a renowned automation server, often requires managing environment variables (env variables) to streamline builds, handle credentials securely, and customize jobs. Understanding how to manage these variables effectively can vastly improve your CI/CD pipelines.

Env variables in Jenkins manage paths and credentials, control build scripts and steps, and allow for parameterized jobs. This tutorial explores effective management techniques, complete with practical examples.

Basic Environment Variables

Start with Jenkins’ own environment variables by navigating to “Manage Jenkins > System Information“. Here, system-level variables are listed. To set a job-specific env variable, use the “EnvInject Plugin“.

Example:

STAGE=production

This variable can be accessed in build steps:

echo '${STAGE}'
# Outputs: production

Parameterized Builds

Parameterized builds allow users to input variables for each build. Add parameters in job configuration:

This build is parameterized

Defining a string parameter:

Name: ENVIRONMENT
Default Value: test

Reference it in scripts:

echo 'Deploying to ${ENVIRONMENT}'
# Outputs: Deploying to test

Using Credentials Securely

Manage sensitive data like passwords using Jenkins Credential Plugin. Add credentials and reference them using the env variable:

withCredentials([string(credentialsId: 'my-credential-id', variable: 'PASSWORD')]) {
    echo 'Password is ${PASSWORD}'
}

Advanced Usage: Pipeline Script

In a Jenkinsfile, leverage the power of pipelines to define env variables:

pipeline {
    agent any
    environment {
        MY_VAR = 'value'
    }
    stages {
        stage('Example') {
            steps {
                echo 'The value of MY_VAR is ${MY_VAR}'
            }
        }
    }
}

This section introduces more complex scenarios like matrices for parallel execution across different environments.

Injecting Env Variables from Scripts

Using the EnvInject plugin or pipeline steps, dynamically create env variables from scripts:

sh 'echo MY_DYNAMIC_VAR=some_value > env.properties'
envInject propertiesFilePath: 'env.properties'

Reflecting real-time changes and facilitating complex, dynamic setups.

Conclusion

Managing env variables in Jenkins boosts automation capabilities, supports complex CI/CD pipelines, and ensures secure handling of credentials. By mastering these techniques, developers can significantly optimize Jenkins-driven processes.