I try to figure out how I can update the global Environment Parameter inside my Pipeline to use with all stages, all agents an all steps. It is hard to set this Environment at one place without to redefine them in each stage. As sample:
pipeline {
agent { label 'linux'}
environment {
CC1="JonDoe"
CC2="DevOps"
CC4=""
}
stages {
stage('Example1') {
environment {
CC3="Compnay"
CC1="Grandma"
CC4="ALT"
}
steps {
sh '''
#print Grandma
echo $CC1
#print DevOps
echo $CC2
#print Compnay
echo $CC3
#print Alt
echo $CC4
printenv
'''
}
}
stage('Example2') {
steps {
sh '''
#Again JonDoe
echo $CC1
#Keep DevOps
echo $CC2
#Empty.not inside printenv
echo $CC3
#Empty.not inside printenv
echo $CC4
printenv
'''
}
}
}
}
So the global nevironment variable is just overwritten temporary.
This is annoying. So I started to research and found:
import hudson.EnvVars;
import hudson.slaves.EnvironmentVariablesNodeProperty;
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
import hudson.util.DescribableList;
import jenkins.model.Jenkins;
public createGlobalEnvironmentVariables(String key, String value){
Jenkins instance = Jenkins.getInstance();
DescribableList<NodeProperty<?>, NodePropertyDescriptor> globalNodeProperties = instance.getGlobalNodeProperties();
List<EnvironmentVariablesNodeProperty> envVarsNodePropertyList = globalNodeProperties.getAll(EnvironmentVariablesNodeProperty.class);
EnvironmentVariablesNodeProperty newEnvVarsNodeProperty = null;
EnvVars envVars = null;
if ( envVarsNodePropertyList == null || envVarsNodePropertyList.size() == 0 ) {
newEnvVarsNodeProperty = new hudson.slaves.EnvironmentVariablesNodeProperty();
globalNodeProperties.add(newEnvVarsNodeProperty);
envVars = newEnvVarsNodeProperty.getEnvVars();
} else {
//We do have a envVars List
envVars = envVarsNodePropertyList.get(0).getEnvVars();
}
envVars.put(key, value)
instance.save()
}
I use with
createGlobalEnvironmentVariables("INGRESS","mydomain.local")
It works like a charm, the disadvantage is this Environment variable will keep in Jenkins because they are Jenkins global.
Anybody knows a similar method to set just the pipeline global environment? Like CC1=“JonDoe” to keep this in the whole pipeline? I think there have to be a groovy script but everything I tried out was not usefull. So I hope I can get a expert tipp here.
I think there have to be something because I also can set Parameters successful with Groovy while Pipeline is running.