How to set "Environment variables" in "Global properties" of global Jenkins configuration programmatically?

20,899 views
Skip to first unread message

mr

unread,
Sep 19, 2014, 3:46:07 AM9/19/14
to jenkins...@googlegroups.com
Hi!
I have some environment variables as List of key-value pairs within the "Global properties" section of the global Jenkins configuration.

I wonder if it is possible to change such a environment variables programmatically, for example by means of a Groovy script?

Regards,
mr

mr

unread,
Sep 22, 2014, 3:23:51 AM9/22/14
to jenkins...@googlegroups.com
Hi Folks!

Do anybody have an idea how to set/change the variables within a Groovy script?

Regards!

Walter Kacynski

unread,
Sep 22, 2014, 1:48:12 PM9/22/14
to jenkins...@googlegroups.com
I use the following script to inject a username and password:

usernamePassword = build.getEnvironment(null)[secret]
def (username, password) = usernamePassword.split(':')

e = new hudson.EnvVars()
e.put(secret + '_USERNAME', username)
e.put(secret + '_PASSWORD', password)
build.environments.add(hudson.model.Environment.create(e))

mr

unread,
Sep 23, 2014, 6:03:51 AM9/23/14
to jenkins...@googlegroups.com
Thanks for the answer!

Where do you inject the username and password? I think you do it into the current build.

But I want to inject a new variable or change an existing variable (like e.g. username or password) into the global configuration, thus next time when I go into the Global Jenkins Configuration UI, I could see the username or password in the section "Global properties".

Is this possible? Is there a package like "hudson.configuration.global" within the API which would allow me to change the environment variable within the global properties jenkins configuration section?

mr

unread,
Sep 29, 2014, 3:17:57 AM9/29/14
to jenkins...@googlegroups.com
Does anybody have an idea???

Jonathann Zenou

unread,
Jan 20, 2015, 11:04:14 AM1/20/15
to jenkins...@googlegroups.com

I seem to have the same issue.
Does someone know what to do to alter a global variable from a job ? Is it even possible ?

Thanks

Victor Volle

unread,
Feb 25, 2015, 3:39:06 PM2/25/15
to jenkins...@googlegroups.com

I have a partial solution, when I have already enabled Global Properties:



the following script works for me:


import jenkins.*

import jenkins.model.*

import hudson.*

import hudson.model.*


nodes = Jenkins.getInstance().getGlobalNodeProperties()

nodes.getAll(hudson.slaves.EnvironmentVariablesNodeProperty.class)

if ( nodes.size() != 1 ) {

  println("error: unexpected number of environment variable containers: "

          + nodes.size()

          + " expected: 1")

} else {

  envVars= nodes.get(0).getEnvVars()

  envVars.put("FOO", "foo")

  ...

  Jenkins.getInstance().save()

  println("okay")

}

I send this script to Jenkins with:

java -jar /tmp/jenkins-cli.jar -s http://localhost:8080/jenkins/ groovy /tmp/jenkins_global_vars.groovy

and the variables are set and persisted. What I haven't yet figured out, is how to enable the Global Properties in the first place


Victor Volle

unread,
Feb 25, 2015, 4:53:27 PM2/25/15
to jenkins...@googlegroups.com
Final solution:

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

newEnvVarsNodeProperty
= null
envVars
= null

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

}

envVars
.put("FOO", "foo")


instance
.save()



Josh Branham

unread,
Nov 9, 2017, 3:58:36 PM11/9/17
to Jenkins Users
Any idea how to make this delete all existing key pairs to ensure only the ones defined in this script  are the ones in Jenkins?

Josh Branham

unread,
Nov 10, 2017, 12:14:17 PM11/10/17
to Jenkins Users
Solved the problem, just add an envVars.clear() to the else statement 

Rakesh Bachu

unread,
Feb 7, 2018, 5:36:50 AM2/7/18
to Jenkins Users
Hi,
This script works fine when tested from 
So i want to do this with a job or a pipeline
how can i make a job or pipeline run this groovy script.

i'm getting random errors when I try to run this groovy script as part of a pipleline.
Thanks,
Rakesh

Victor Volle

unread,
Feb 7, 2018, 7:02:00 AM2/7/18
to Jenkins Users
Which error(s)?

ZillaYT

unread,
Jul 26, 2018, 10:52:49 AM7/26/18
to Jenkins Users
I copy/pasted this code in my Jenkinsfile (including import calls above) and I get

an exception which occurred:
       
in field groovy.lang.Closure.delegate
       
in object org.jenkinsci.plugins.workflow.cps.CpsClosure2@4d78782
       
in field org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.closures
       
in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@41f97d3f
       
in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@41f97d3f
Caused: java.io.NotSerializableException: hudson.model.Hudson
        at org
.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:860)
        at org
.jboss.marshalling.river.BlockMarshaller.doWriteObject(BlockMarshaller.java:65)
        at org
.jboss.marshalling.river.BlockMarshaller.writeObject(BlockMarshaller.java:56)
        at org
.jboss.marshalling.MarshallerObjectOutputStream.writeObjectOverride(MarshallerObjectOutputStream.java:50)
        at org
.jboss.marshalling.river.RiverObjectOutputStream.writeObjectOverride(RiverObjectOutputStream.java:179)
        at java
.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:344)
        at java
.util.LinkedHashMap.internalWriteEntries(LinkedHashMap.java:333)
        at java
.util.HashMap.writeObject(HashMap.java:1362)
        at sun
.reflect.GeneratedMethodAccessor139.invoke(Unknown Source)
        at sun
.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java
.lang.reflect.Method.invoke(Method.java:498)
        at org
.jboss.marshalling.reflect.SerializableClass.callWriteObject(SerializableClass.java:273)
        at org
.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:976)
        at org
.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
        at org
.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
        at org
.jboss.marshalling.river.BlockMarshaller.doWriteObject(BlockMarshaller.java:65)
        at org
.jboss.marshalling.river.BlockMarshaller.writeObject(BlockMarshaller.java:56)
        at org
.jboss.marshalling.MarshallerObjectOutputStream.writeObjectOverride(MarshallerObjectOutputStream.java:50)
        at org
.jboss.marshalling.river.RiverObjectOutputStream.writeObjectOverride(RiverObjectOutputStream.java:179)
        at java
.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:344)
        at com
.cloudbees.groovy.cps.SerializableScript.writeObject(SerializableScript.java:26)
        at sun
.reflect.GeneratedMethodAccessor149.invoke(Unknown Source)
        at sun
.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java
.lang.reflect.Method.invoke(Method.java:498)
        at org
.jboss.marshalling.reflect.SerializableClass.callWriteObject(SerializableClass.java:273)
        at org
.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:976)
        at org
.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
        at org
.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
        at org
.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
        at org
.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
        at org
.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
        at org
.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
        at org
.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
        at org
.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
        at org
.jboss.marshalling.river.BlockMarshaller.doWriteObject(BlockMarshaller.java:65)
        at org
.jboss.marshalling.river.BlockMarshaller.writeObject(BlockMarshaller.java:56)
        at org
.jboss.marshalling.MarshallerObjectOutputStream.writeObjectOverride(MarshallerObjectOutputStream.java:50)
        at org
.jboss.marshalling.river.RiverObjectOutputStream.writeObjectOverride(RiverObjectOutputStream.java:179)
        at java
.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:344)
        at java
.util.HashMap.internalWriteEntries(HashMap.java:1785)
        at java
.util.HashMap.writeObject(HashMap.java:1362)
        at sun
.reflect.GeneratedMethodAccessor139.invoke(Unknown Source)
        at sun
.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java
.lang.reflect.Method.invoke(Method.java:498)
        at org
.jboss.marshalling.reflect.SerializableClass.callWriteObject(SerializableClass.java:273)
        at org
.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:976)
        at org
.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
        at org
.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
        at org
.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
        at org
.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
        at org
.jboss.marshalling.AbstractObjectOutput.writeObject(AbstractObjectOutput.java:58)
        at org
.jboss.marshalling.AbstractMarshaller.writeObject(AbstractMarshaller.java:111)
        at org
.jenkinsci.plugins.workflow.support.pickles.serialization.RiverWriter.lambda$writeObject$0(RiverWriter.java:144)
        at org
.jenkinsci.plugins.scriptsecurity.sandbox.groovy.GroovySandbox.runInSandbox(GroovySandbox.java:108)
        at org
.jenkinsci.plugins.workflow.support.pickles.serialization.RiverWriter.writeObject(RiverWriter.java:143)
        at org
.jenkinsci.plugins.workflow.cps.CpsThreadGroup.saveProgram(CpsThreadGroup.java:482)
        at org
.jenkinsci.plugins.workflow.cps.CpsThreadGroup.saveProgram(CpsThreadGroup.java:458)
        at org
.jenkinsci.plugins.workflow.cps.CpsThreadGroup.saveProgramIfPossible(CpsThreadGroup.java:445)
        at org
.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:372)
        at org
.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$200(CpsThreadGroup.java:83)
        at org
.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:244)
        at org
.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:232)
        at org
.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:64)
        at java
.util.concurrent.FutureTask.run(FutureTask.java:266)
        at hudson
.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:131)
        at jenkins
.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
        at jenkins
.security.ImpersonatingExecutorService$1.run(ImpersonatingExecutorService.java:59)
        at java
.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java
.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java
.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java
.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java
.lang.Thread.run(Thread.java:745)
Finished: FAILURE



On Wednesday, February 25, 2015 at 4:53:27 PM UTC-5, Victor Volle wrote:

Mark Waite

unread,
Jul 26, 2018, 11:08:47 AM7/26/18
to jenkins...@googlegroups.com
On Thu, Jul 26, 2018 at 8:52 AM ZillaYT <zil...@gmail.com> wrote:
I copy/pasted this code in my Jenkinsfile (including import calls above) and I get

That code is a global configuration script which needs to be executed from the "Groovy console" of the Jenkins server.

It can't be used from a Jenkinsfile.

Mark Waite
 
--
You received this message because you are subscribed to the Google Groups "Jenkins Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jenkinsci-use...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/jenkinsci-users/7cb7ebc7-8dff-439f-8856-91b0eba2cb70%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

ZillaYT

unread,
Jul 26, 2018, 11:14:23 AM7/26/18
to Jenkins Users
I just had to do this to fix it.

Jenkins instance = Jenkins.getInstance()
def globalNodeProperties
= instance.getGlobalNodeProperties()
def envVarsNodePropertyList
= globalNodeProperties.getAll(hudson.slaves.EnvironmentVariablesNodeProperty.class)
def newEnvVarsNodeProperty
= null
def envVars
= null

        at org
.jboss.marshalling</span

Nick Mellor

unread,
Aug 5, 2018, 9:17:15 PM8/5/18
to Jenkins Users
Hi Zilla, this doesn't work for me. I get:

java.io.NotSerializableException: hudson.slaves.EnvironmentVariablesNodeProperty

Any ideas?

Thanks,

Nick

Nick Mellor

unread,
Aug 5, 2018, 9:24:34 PM8/5/18
to Jenkins Users
Just to be clear: I had working code in Jenkins 2.19 that looked like this:

def appVersion(String app, incrementPatch = true) {
  assert app.toLowerCase() in ['appName'], "No such project implemented: '$app'"
  def version = [
          elms: env.VERSION_OVERRIDE,
          lacm: env.LACM_VERSION_OVERRIDE,
  ].get(app.toLowerCase())
  if (!version) {
    // auto-generate version number if no manual version given
    def nodes = Jenkins.instance.globalNodeProperties
    nodes.getAll(hudson.slaves.EnvironmentVariablesNodeProperty.class)
    if (nodes.size() != 1) {
      echo "Error: unexpected number of environment variable containers: ${nodes.size()} (expected 1)"
    } else {
      def envVars = nodes[0].envVars
      // last patch number used is maintained per major/minor version
      // stored in e.g. 'PATCH_VERSION_17.10' in Jenkins
      def majorMinorVersion = env.MONTHLY_RELEASE_VERSION
      def majorMinorPatchVar = "${app.toUpperCase()}_PATCH_VERSION_${majorMinorVersion}"
      String currentPatchVersion = envVars[majorMinorPatchVar]
      if (currentPatchVersion) {
        if (incrementPatch) {
          currentPatchVersion = (Integer.parseInt(currentPatchVersion) + 1) as String
        }
      } else {
        currentPatchVersion = '1'
      }
      // NB timestamp needs to be set statically by the pipeline
      // to maintain version parity between pipeline stages
      def timestamp = env.BUILD_TIMESTAMP
      version = "$majorMinorVersion.$currentPatchVersion-$timestamp"
      // create or update auto patch version for this major/minor build
      // this will create new variable in Jenkins if necessary
      envVars[majorMinorPatchVar] = currentPatchVersion
      Jenkins.instance.save()
    }
  }
  echo "Autogenerated ${app.toUpperCase()} version is '$version'"
  return version
}



Have had trouble since moving to Jenkins 2.31.

Hey guys, please hold the (no doubt excellent) advice to upgrade to the latest Jenkins: I'm at a large corporate that doesn't (can't, won't) move quickly on Jenkins version.

Thanks for any input,

Nick

Nick Mellor

unread,
Aug 5, 2018, 9:25:44 PM8/5/18
to Jenkins Users
the problem appears to be

hudson.slaves.EnvironmentVariablesNodeProperty.class

 passed as a parameter, but which can't be serialised.

Cristian Banarescu

unread,
Jan 30, 2019, 7:33:32 AM1/30/19
to Jenkins Users
Hey man! Your solution also worked for me! Thank you very much!
Reply all
Reply to author
Forward
0 new messages