Jenkins管道:在管道中使用全局变量

时间:2019-01-23 19:22:09

标签: jenkins-pipeline

我有一个包含多个阶段的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块中使用时,其他两个变量HOURwhen可以正常工作。有想法吗?

1 个答案:

答案 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一起使用的值包括:

  • TimerTrigger
  • UserId
  • (其他?例如SCM触发器吗?)