Vin*_*ent 7 jenkins jenkins-pipeline
我的repo中有一个带有Jenkinsfile的multibranch管道,我可以在每次提交时使用我的CI工作流程(构建和单元测试 - > deploy-dev - >批准 - > deploy-QA - >批准 - > deploy-prod) .我想做的是在第一阶段构建和单元测试的夜间构建中添加SonarQube Analysis.由于我的构建是由Gitlab触发的,我已经定义了我的管道触发器如下:
pipeline {
...
triggers {
gitlab(triggerOnPush: true, triggerOnMergeRequest: true, branchFilterType: 'All')
}
...
}
Run Code Online (Sandbox Code Playgroud)
为了设置我的夜间构建,我添加了
triggers {
...
cron('H H * * *')
}
Run Code Online (Sandbox Code Playgroud)
但是现在,如果我们只在晚上构建由cron表达式触发的作业,如何执行分析步骤?
我简化的构建阶段如下所示:
stage('Build & Tests & Analysis') {
// HERE THE BEGIN SONAR ANALYSIS (to be executed on nightly builds)
bat 'msbuild.exe ...'
bat 'mstest.exe ...'
// HERE THE END SONAR ANALYSIS (to be executed on nightly builds)
}
Run Code Online (Sandbox Code Playgroud)
小智 7
有如何获取构建触发器信息的方法.这里描述:https: //jenkins.io/doc/pipeline/examples/#get-build-cause
你也可以检查一下: 如何在工作流程中获得$ CAUSE
对您的案例非常好的参考是https://hopstorawpointers.blogspot.com/2016/10/performing-nightly-build-steps-with.html.以下是该来源的功能,完全符合您的需求:
// check if the job was started by a timer
@NonCPS
def isJobStartedByTimer() {
def startedByTimer = false
try {
def buildCauses = currentBuild.rawBuild.getCauses()
for ( buildCause in buildCauses ) {
if (buildCause != null) {
def causeDescription = buildCause.getShortDescription()
echo "shortDescription: ${causeDescription}"
if (causeDescription.contains("Started by timer")) {
startedByTimer = true
}
}
}
} catch(theError) {
echo "Error getting build cause"
}
return startedByTimer
}
Run Code Online (Sandbox Code Playgroud)
对我来说,最简单的方法是在构建触发器中定义一个 cron 并使用以下命令验证夜间阶段的时间when expression:
pipeline {
agent any
triggers {
pollSCM('* * * * *') //runs this pipeline on every commit
cron('30 23 * * *') //run at 23:30:00
}
stages {
stage('nightly') {
when {//runs only when the expression evaluates to true
expression {//will return true when the build runs via cron trigger (also when there is a commit at night between 23:00 and 23:59)
return Calendar.instance.get(Calendar.HOUR_OF_DAY) in 23
}
}
steps {
echo "Running the nightly stage only at night..."
}
}
}
}
Run Code Online (Sandbox Code Playgroud)