How to create environment variables with a script?

31 views
Skip to first unread message

Faad Sayaou

unread,
Mar 15, 2019, 12:49:51 PM3/15/19
to Jenkins Users
Hi,
Is there any method of creating environment variables via a script? The goal is to have a script that I can run whenever I have a freshly installed jenkins instance. Then I don't have to set all the variables manually.
Same question also for pipelines.

Thanks

Ivan Fernandez Calvo

unread,
Mar 16, 2019, 12:35:56 PM3/16/19
to Jenkins Users
For pipelines take a look to the environment directive documentation https://jenkins.io/doc/pipeline/tour/environment also you can define variable by asigning a value to env variable

script { env.VARIABLE_NAME = ’value’ }

See also
https://jenkins.io/doc/book/pipeline/shared-libraries/
https://wiki.jenkins.io/plugins/servlet/mobile?contentId=58000129#content/view/58000129


To set environment variables or properties at Jenkins start time you could use init scripts https://wiki.jenkins.io/plugins/servlet/mobile?contentId=38142057#content/view/3814205 or CasC https://jenkins.io/projects/jcasc/

Faad Sayaou

unread,
Mar 16, 2019, 2:26:36 PM3/16/19
to Jenkins Users
Hi, I found a way of creating it via the script console (in reference to an answer in this group). Maybe this could help others in the future

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("Username", "myUsername")
envVars
.put("Password", "myPassword")




instance
.save()

you can add as many as you want and this would create the env vars. I also found the piece of code on StackOverflow which creates a pipeline but I would like to create multiple pipelines and not just one. any idea how to do this with the code below?

import hudson.plugins.git.*;

def scm = new GitSCM("g...@github.com/yourRepo.git")
scm.branches = [new BranchSpec("*/TestBranch")];

def flowDefinition = new org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition(scm, "Jenkinsfile")

def parent = Jenkins.instance
def job = new org.jenkinsci.plugins.workflow.job.WorkflowJob(parent, "New Job")
job.definition = flowDefinition

parent.reload()
Reply all
Reply to author
Forward
0 new messages