我有一个包含多个阶段的Jenkins管道,这将需要知道如何触发构建(由用户,计时器等),并且我希望避免在每个阶段重复以下行:
currentBuild.rawBuild.getCauses()[0].class.getName().contains('TimerTriggerCause')
在每个when
块中使用该命令时,它都能按预期工作,但是在environment
块中放置时,它总是失败:
[Pipeline] node
Running on Jenkins in /var/lib/jenkins/jobs/test-pipeline/workspace
[Pipeline] {
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Stage on timer)
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
java.lang.NoSuchMethodError: No such DSL method '$' found among steps [archive, bat, build, catchError...zip] or globals [currentBuild, docker, env, params, pipeline, scm]
at org.jenkinsci.plugins.workflow.cps.DSL.invokeMethod(DSL.java:199)
at org.jenkinsci.plugins.workflow.cps.CpsScript.invokeMethod(CpsScript.java:122)
at sun.reflect.GeneratedMethodAccessor513.invoke(Unknown Source)
Jenkins脚本:
pipeline {
agent {
label 'master'
}
environment {
DAY = Calendar.getInstance().get(Calendar.DAY_OF_WEEK)
HOUR = Calendar.getInstance().get(Calendar.HOUR_OF_DAY)
ONTIMER = currentBuild.rawBuild.getCauses()[0].class.getName().contains('TimerTriggerCause')
}
stages {
stage('Stage on timer') {
when {
expression {
return (${ONTIMER} && (${DAY} != Calendar.SATURDAY && ${DAY} != Calendar.SUNDAY))
}
}
steps {
echo "on timer..."
}
}
}
}
在DAY
块中使用时,其他两个变量HOUR
和when
可以正常工作。有想法吗?
答案 0 :(得分:0)
经过反复试验后,我得到了想要的行为。
处理环境变量时的when
条件使用略有不同的语法。它具有自己的environment
关键字,然后可以使用:
when {
environment name: 'ONTIMER', value: 'true'
}
作为奖励,在when
块中也使用整数值:
when {
allOf {
environment name: 'ONTIMER', value: 'true'
expression { return Integer.parseInt(env.HOUR) < 11 }
}
}
更好,可以使用triggeredBy
关键字并对此采取行动:
when {
anyOf {
expression { return params.RUN }
allOf {
triggeredBy "TimerTrigger"
expression {
Integer.parseInt(env.HOUR) < 13
}
}
}
}
与triggeredBy
一起使用的值包括: