I try tofigure out how environment variable in jenkins are working and I get confused. Maybe someone can help to find my missunderstanding:
Pipleline:
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)
envVars.override("HELM_CHART_NAME", "humpty")
instance.save()
}
pipeline{
agent {
kubernetes {
yaml """\
apiVersion: v1
kind: Pod
metadata:
labels:
pipeline: deploy
spec:
containers:
- name: maven
image: maven:3.5.4-openjdk11
imagePullPolicy: Always
command:
- cat
tty: true
""".stripIndent()
}
}
environment{
HELM_CHART_NAME = "foo"
}
stage('Build'){
agent { label 'agentx'}
steps {
script {
createGlobalEnvironmentVariables("HELM_CHART_NAME1", "test")
//ANCHOR1
echo "${HELM_CHART_NAME1}"
echo "${HELM_CHART_NAME}"
}
timestamps {
withMaven(jdk: 'JDK11.0.8_10', maven: 'apache-maven-3.5.4', mavenLocalRepo: 'mvn.repo', mavenOpts: '-Xrs -Xmx1024m -Xss1m', publisherStrategy: 'EXPLICIT') {
sh label: 'Build', script: '''
#ANCHOR2
echo ${HELM_CHART_NAME1}
echo ${HELM_CHART_NAME}
'''
}
}
}
}
}
If I add a new global variable with
createGlobalEnvironmentVariables("HELM_CHART_NAME1", "test")
Evrything works fine. But if I try to change an existing environment variable, that I define inside the global environment block, it will not change anything. At ANCHOR 1 I get
09:38:13 + echo test
09:38:13 + echo foo
At ANCHOR 2 I get the same
What s my flaw in to change an existing (global defned) environment variable?
envVars.override("HELM_CHART_NAME", "humpty")
From what I read is ,that override is the method to change existing and put is for create new one.
put works, override not.
If I add a sh 'printenv' the output show me both environment variables but also HELM_CHART_NAME as still "foo"
The only thing that I think is that my hudson function only read global and not local environment variables? But how to access those locals defined in "environment{}" block?