如何在 Jenkins 声明式管道中处理夜间构建 [英] How to handle nightly build in Jenkins declarative pipeline

查看:22
本文介绍了如何在 Jenkins 声明式管道中处理夜间构建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的仓库中有一个带有 Jenkinsfile 的多分支管道,并且我能够拥有我的 CI 工作流程(构建和单元测试 -> 部署开发 -> 批准 -> 部署 QA -> 批准 -> 部署产品) 在每次提交时.我想做的是在第一阶段构建和夜间构建中添加 SonarQube 分析.单元测试.由于我的构建是由 Gitlab 触发的,因此我将管道触发器定义如下:

I have a multibranch pipeline with a Jenkinsfile in my repo and I am able to have my CI workflow (build & unit tests -> deploy-dev -> approval -> deploy-QA -> approval -> deploy-prod) on every commit. What I would like to do is add SonarQube Analysis on nightly builds in the first phase build & unit tests. Since my build is triggerd by Gitlab I have defined my pipeline triggers as follow :

pipeline {
    ...
    triggers {
        gitlab(triggerOnPush: true, triggerOnMergeRequest: true, branchFilterType: 'All')
    }
    ...
}

为了设置我的夜间构建,我添加了

To setup my nightly build I have added

triggers {
    ...
    cron('H H * * *')
}

但是现在,如果我们只是在晚上构建由 cron 表达式触发的作业,如何执行分析步骤?

But now, how to execute analysis step if we are only building the job triggered by the cron expression at night ?

我的简化构建阶段如下所示:

My simplified build stage looks as follow :

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)
}

推荐答案

这里有获取构建触发信息的方法.这里描述:https://jenkins.io/doc/pipeline/examples/#get-build-原因

There is the way how to get build trigger information. It is described here: https://jenkins.io/doc/pipeline/examples/#get-build-cause

您也可以检查一下:如何在工作流中获取 $CAUSE

您的案例非常好的参考是 https:///hopstorawpointers.blogspot.com/2016/10/performing-nightly-build-steps-with.html.以下是该来源中与您的需求完全匹配的函数:

Very good reference for your case is https://hopstorawpointers.blogspot.com/2016/10/performing-nightly-build-steps-with.html. Here is the function from that source that exactly matches your need:

// 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
}

这篇关于如何在 Jenkins 声明式管道中处理夜间构建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆