在Jenkins1中,我们有一个脚本来设置环境变量,诸如此类:
//...imports
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();
envVars.put(NEW_VAR, "toto");
} else {
for (property in envVarsNodePropertyList) {
envVars = property.getEnvVars();
envVars.put("EXISTING_VAR","tata");
}
}
instance.save()
今天,我们正在使用具有jenkinsfile功能的Jenkins2,我想知道如何将相同的事情制作到jenkinsfile中?
这是否可行,如果可以,有没有更好的方法? :
def setEnvVar() {
script {
//all the script above
}
}
pipeline {
agent any
tools {
maven 'Maven3_6'
jdk 'Jdk8'
}
stages {
stage ('Initialize') {
steps {
setEnvVar()
}
}
...
EDIT :假设我有一个现有的env变量,LAST_DEPLOY =“ 0.1”使用:
environment {
LAST_DEPLOY = "0.2"
}
只会修改当前执行的变量,最后以某种方式将其重置为“ 0.1”,我希望修改能够持续到下一个版本。
答案 0 :(得分:0)
只需查看官方文档,https://jenkins.io/doc/pipeline/tour/environment/
environment {
NODE_ENV = 'sandbox'
DB_NAME = 'db_common'
}
,然后您可以在 sh 步骤中使用它,例如$ {NODE_ENV}
答案 1 :(得分:0)
所以我发现的当前解决方案是将其添加到jenkins文件中:
import jenkins.*
import jenkins.model.*
import hudson.*
import hudson.model.*
import hudson.slaves.*
def updateEnvVar() {
script {
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();
envVars.put(NEW_VAR, "toto");
} else {
for (property in envVarsNodePropertyList) {
envVars = property.getEnvVars();
envVars.put("EXISTING_VAR","tata");
}
}
instance.save()
}
}
pipeline {
...
首先,Jenkins将发送一些安全性错误,您可以通过管理Jenkins->处理中脚本批准->批准
来修复(后果自负)。cf: Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject https://jenkins.io/doc/book/managing/script-approval/