Programatically add Environment Variables to a Jenkins Instance

We prepare our Jenkins as Docker containers as described in One-Click Jenkins Setup

These days a new Groovy script has been added to the Dockerfile:

COPY add-global-environment-variables.groovy /var/jenkins_home/init.groovy.d/

As you might expect this Groovy script add global environment variables.

import hudson.slaves.EnvironmentVariablesNodeProperty
import jenkins.model.Jenkins

instance = Jenkins.getInstance()
globalNodeProperties = instance.getGlobalNodeProperties()
envVarsNodePropertyList = globalNodeProperties.getAll(EnvironmentVariablesNodeProperty.class)

newEnvVarsNodeProperty = null
envVars = null

if ( envVarsNodePropertyList == null || envVarsNodePropertyList.size() == 0 ) {
  newEnvVarsNodeProperty = new EnvironmentVariablesNodeProperty();
  envVars = newEnvVarsNodeProperty.getEnvVars()
} else {
  envVars = envVarsNodePropertyList.get(0).getEnvVars()

envVars.put("PLANETS_HOMEPAGE_URL", "")

Many thanks to all who contributed to How to set "Environment variables" in "Global properties" of global Jenkins configuration programmatically?

If you got so far you might also like our other Jenkins related posts:

How to Checkout a Gerrit Change in a Jenkins Sandbox Pipeline

How-To manipulate a Jenkins Job with the Script Console

Adding Views and Descriptions to Jenkins - The Groovy Way

Show Comments