我试图使用系统groovy脚本作为构建步骤操作我们的一个作业中的一些变量:
//Current Thread run
def thr = Thread.currentThread()
def current_build = thr?.executable
//Get upstream job
def parent_build = current_build.getCause(hudson.model.Cause.UpstreamCause).getUpstreamRun()
//Upstream job build vars
def parentMap = parent_build.getBuildVariables()
println "ParentbuildMap.get(OSType) = " + parentMap.get("OSType")
println "ParentbuildMap.get(DBType) = " + parentMap.get("DBType")
//TODO insert SQL script here to populate OS_MACHINE and DB_MACHINE
def OS_MACHINE = parentMap.get("OSType") + ": ##Machine_Name##"
def DB_MACHINE = parentMap.get("DBType") + ": **Machine_Name**"
现在,当我尝试打印它们时,它会打印出正确的值:
println "OS_MACHINE = " + OS_MACHINE
println "DB_MACHINE = " + DB_MACHINE
但是当我尝试以下操作时,它只会打印出null:
println build.buildVariableResolver.resolve(OS_MACHINE)
即使我尝试这样做,也会打印出null:
def thr = Thread.currentThread()
def current_build = thr?.executable
def buildMap = build.getBuildVariables()
println "buildMap.get(OS_MACHINE) = " + buildMap.get("OS_MACHINE")
println "buildMap.get(DB_MACHINE) = " + buildMap.get("DB_MACHINE")
当我尝试这个时:
def params = [
new StringParameterValue('JOB_OS_MACHINE', OS_MACHINE),
new StringParameterValue('JOB_DB_MACHINE', DB_MACHINE),
]
build.addAction(new ParametersAction(params))
println "buildMap.get(JOB_OS_MACHINE) = " + buildMap.get("JOB_OS_MACHINE")
println "buildMap.get(JOB_DB_MACHINE) = " + buildMap.get("JOB_DB_MACHINE")
在这种情况下,如果我用普通字符串
替换OS_MACHINE和DB_MACHINE,它甚至可以工作我现在恢复了在新工作上运行一个非常简单的脚本,脚本取自: https://wiki.jenkins-ci.org/display/JENKINS/Parameterized+System+Groovy+script
import hudson.model.*
// get current thread / Executor
def thr = Thread.currentThread()
// get current build
def build = thr?.executable
// ... or if you want the parameter by name ...
def hardcoded_param = "FOOBAR"
def resolver = build.buildVariableResolver
def hardcoded_param_value = resolver.resolve(hardcoded_param)
println "param ${hardcoded_param} value : ${hardcoded_param_value}"
其中也打印为null。
对于我的生活,我无法理解这里出了什么问题......任何人都可以帮助我吗?
答案 0 :(得分:2)
可以在Jenkins用户列表存档中找到solution。您正在创建新的StringParameterValue对象并将它们添加到构建ParametersAction中。
上面链接的解决方案并不像我所写的那样(可能是因为我使用的是Jenkins 1.466.2的旧版本)。无法识别createUpdated方法,因此我将其复制到我的代码中,我将在下面发布。
// sets build parameters based on the given map
// only supports StringParameterValue
def setBuildParameters(parmMap) {
def npl = new ArrayList<StringParameterValue>()
for (k in parmMap.keySet()) {
npl.add(new StringParameterValue(k, parmMap.get(k)))
}
def newPa = null
def oldPa = build.getAction(ParametersAction.class)
if (oldPa != null) {
for (oldp in oldPa) {
if (! parmMap.containsKey(oldp.name)) { //oldp was not overridden by the new list
npl.add(oldp)
}
}
build.actions.remove(oldPa)
}
newPa = new ParametersAction(npl)
build.actions.add(newPa)
}
答案 1 :(得分:0)
很抱歉只在现在添加答案,但我遇到同样的问题,阅读这篇文章给我一个解决方案:
因此,解析器将在env参数中找到值,作为jenkins构建变量。
这样做可以解决我的问题。